Allow easier trait registration

This commit is contained in:
fullwall 2012-01-22 15:31:49 +08:00
parent aa6c20dcd5
commit 8ffc62a9a0
4 changed files with 35 additions and 29 deletions

View File

@ -4,7 +4,6 @@ import java.io.File;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.DataKey;
import net.citizensnpcs.api.Factory;
import net.citizensnpcs.api.exception.NPCLoadException;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.npc.trait.Character;
@ -92,12 +91,7 @@ public class Citizens extends JavaPlugin {
// TODO possibly separate this out some more
private void setupNPCs() throws NPCLoadException {
traitManager.registerTraitFactory("location", new Factory<SpawnLocation>() {
@Override
public SpawnLocation create() {
return new SpawnLocation();
}
});
traitManager.registerTrait("location", SpawnLocation.class);
int spawned = 0;
for (DataKey key : saves.getKey("npc").getIntegerSubKeys()) {
int id = Integer.parseInt(key.name());

View File

@ -4,7 +4,6 @@ import java.util.HashMap;
import java.util.Map;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.Factory;
import net.citizensnpcs.api.event.NPCDespawnEvent;
import net.citizensnpcs.api.event.NPCSpawnEvent;
import net.citizensnpcs.api.npc.NPC;
@ -177,24 +176,4 @@ public class CitizensNPC implements NPC {
public CraftNPC getHandle() {
return mcEntity;
}
public static class ReflectionTraitFactory implements Factory<Trait> {
private final Class<? extends Trait> clazz;
public ReflectionTraitFactory(Class<? extends Trait> clazz) {
this.clazz = clazz;
}
@Override
public Trait create() {
try {
return clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
}

View File

@ -20,9 +20,31 @@ public class CitizensTraitManager implements TraitManager {
}
@Override
public void registerTraitFactory(String name, Factory<? extends Trait> factory) {
public void registerTrait(String name, Class<? extends Trait> clazz) {
registerTraitWithFactory(name, new ReflectionFactory(clazz));
}
@Override
public void registerTraitWithFactory(String name, Factory<? extends Trait> factory) {
if (registered.get(name) != null)
throw new IllegalArgumentException("trait factory already registered");
registered.put(name, factory);
}
private static class ReflectionFactory implements Factory<Trait> {
private final Class<? extends Trait> clazz;
private ReflectionFactory(Class<? extends Trait> clazz) {
this.clazz = clazz;
}
@Override
public Trait create() {
try {
return clazz.newInstance();
} catch (Exception ex) {
return null;
}
}
}
}

View File

@ -0,0 +1,11 @@
package net.citizensnpcs.test;
import org.junit.Test;
public class StorageTest {
@Test
public void testYaml() {
}
}