samedi 17 décembre 2016

Get non-static block variable of a class

I have this class: Rat.java

public class Rat extends Mob {

{
    spriteClass = RatSprite.class;

    HP = HT = 8;
    defenseSkill = 2;

    maxLvl = 5;
}

@Override
public int damageRoll() {
    return Random.NormalIntRange( 1, 4 );
}

@Override
public int attackSkill( Char target ) {
    return 8;
}

@Override
public int drRoll() {
    return Random.NormalIntRange(0, 1);
}
}

And need to access its field "spriteClass" knowing the class' canonical name.

How does one do this kind of thing?

What I have done so far:

public Class<? extends CharSprite> getSprite(String e){
    if(e.indexOf("Hero") != -1) return HeroSprite.class;

    Class<?> cl = null;

    try {
        cl = Class.forName(e);
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }
    /*
    Field f = null;
    try {
        Log.d("ssss", cl.toString());
        if(cl != null) f = cl.getField("spriteClass");
    } catch (NoSuchFieldException e1) {
        e1.printStackTrace();
    }
    try {
        if(f != null){
            Class c = (Class) f.get(this);
            return c;
        }
    } catch (IllegalAccessException e1) {
        e1.printStackTrace();
    }*/
    Constructor<?> ctor = null;
    try {
        ctor = cl.getConstructor();
    } catch (NoSuchMethodException e1) {
        e1.printStackTrace();
    }
    try {
        Object object = ctor.newInstance();
        object.



    } catch (InstantiationException e1) {
        e1.printStackTrace();
    } catch (IllegalAccessException e1) {
        e1.printStackTrace();
    } catch (InvocationTargetException e1) {
        e1.printStackTrace();
    }
    return null;
}

I guess you can access non-static block when the object is created.





Aucun commentaire:

Enregistrer un commentaire