Java - Dynamically Alter Subclass from Parentclass
I have a class, which has the following:
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));
}
}
}
}
My idea is to somehow use a method like so:
public void setAttribute(Class attribute.getClass(), int value) {
}
In this method, the caller would specify the type of attribute to alter (such as strength, intelligence, etc.), and a process would go through the vector array full of Attributes listed above to determine which attribute to manipulate, by identifying whe开发者_JAVA百科ther or not the passed attribute subclass was equal to a subclass from the mentioned vector. If this was the case, the subclass within the vector would be altered.
Is this possible? The main reason why I'm asking this because I'm not sure if obj.getClass()/getType() == obj2.getClass()/getType() will take into consideration subclasses as well.
Yes, you can do it. obj.getClass() will return exact class of obj, regardless which type obj you declare. I advice you do not use reflection, where it is possible. You can replace Attribute inheritance with enum:
enum Attribute {
STREGTH, AGILITY, SPEED, ...;
}
And have something like:
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);
}
}
What you are basically looking for is Class.isAssignableFrom(...). It will check if the current class is the same or a superclass of the as parameter given class.
You have simply to iterate through your array and remove the attribute which is duplicate and add the new attribute to it.
精彩评论