我有一个类,它包含以下内容:
final class Attributes {
Attribute agility;
Attribute endurance;
Attribute intelligence;
Attribute intuition;
Attribute luck;
Attribute speed;
Attribute strength;
private ArrayList<Attribute> attributes;
private boolean initialized = false;
public Attributes() throws IllegalAccessException {
initializeAttributes();
store();
}
public ArrayList<Attribute> getAttributes() {
return attributes;
}
private void initializeAttributes() {
if (!initialized) {
agility = new Agility();
endurance = new Endurance();
intelligence = new Intelligence();
intuition = new Intuition();
luck = new Luck();
speed = new Speed();
strength = new Strength();
initialized = true;
}
}
private void store() throws IllegalAccessException {
Field[] fields = this.getClass().getDeclaredFields();
attributes = new ArrayList<Attribute>();
if (initialized) {
for (Field f : fields) {
if (f.getType() == Attribute.class) {
attributes.add((Attribute)f.get(this));
}
}
}
}我的想法是以某种方式使用如下方法:
public void setAttribute(Class attribute.getClass(), int value) {
}在此方法中,调用者将指定要更改的属性类型(如强度、智能等),并且进程将遍历上面列出的充满属性的向量数组,通过识别传递的属性子类是否等于所述向量的子类来确定要操作哪个属性。如果是这种情况,向量中的子类将会改变。
这个是可能的吗?我问这个的主要原因是我不确定obj.getClass()/getType() == obj2.getClass()/getType()是否也会考虑子类。
发布于 2011-06-24 04:17:23
是的,你能做到。obj.getClass()将返回obj的确切类,而不管您声明的是哪种类型的obj。我建议您在可能的情况下不要使用反射。您可以使用枚举替换属性继承:
enum Attribute {
STREGTH, AGILITY, SPEED, ...;
}并拥有以下内容:
public final class Attributes {
private Map<Attribute, Integer> attributes = new EnumMap(Attribute.class);
private void initializeAttributes() {
if (!initialized) {
for(Attribute att : Attribute.values()) {
attributes.put(att, 0);
}
initialized = true;
}
}
public void setAttribute(Attribute attribute, int value) {
attributes.put(attribute, value);
}
}发布于 2011-06-24 04:21:34
你基本上要找的是Class.isAssignableFrom(...)。它将检查当前类是否与给定的as参数类的超类相同。
您只需迭代数组,删除重复的属性并向其添加新属性即可。
https://stackoverflow.com/questions/6459926
复制相似问题