jeudi 21 mai 2015

Setting the Value of a Field Without Knowing The Type Java Reflection

I have been working on this problem for more than 12 hours without success so if anyone can help with this or provide a different solution I will be eternally grateful. The main problem iv'e been running into is changing fields with the class inheritance structure which i will attempt to explain:

The "craftPlayer" variable is an instance of CraftPlayer which is a child class of CraftEntity. The CraftEntity class contains a Entity object which has the variable "uniqueID". So Basically all i'm trying to do is change that uniqueID variable for "craftPlayer". I don't have access to any of the classes so i'm using reflection. The problem i'm running into currently is trying to change the Entity variable which is inside "craftPlayer" the but i can't figure out a way to get the instance of that class as the "entity" variable is really an instance of EntityPlayer and not Entity

I realize this was very poorly explained so ask as many clarifying questions as you want. Any help would be much appreciated.

        CraftEntity craftPlayer = (CraftEntity) player;
        @SuppressWarnings("unchecked")
        Class<CraftEntity> craftEntityClass = getCraftEntityClass((Class<CraftEntity>) craftPlayer.getClass());

        for (Field field : craftEntityClass.getDeclaredFields()) {
            field.setAccessible(true);
            if (field.getName().equals("entity")) {
                Object object = field.get(craftPlayer);
                Entity entity = (Entity) object;
                entity.uniqueID = new UUID(0L, 0L);
                field.set(entity, entity); //"entity" is really an instance of EntityPlayer which is a subclass of Entity so i am unable to change the field because upclassing does not seem to work
                break;
            }
        }





Aucun commentaire:

Enregistrer un commentaire