简体   繁体   中英

Java getDeclaredFields of a class with missing dependencies

I am having trouble getting the declared fields of an Object that is missing/not using specific dependencies.

Field[] fields = OBJECT.getClass().getDeclaredFields();

throws a NoClassDefFoundError when that object has imports to missing classes.

The reason I want to do this is for a Bukkit plugin. I want to get the fields of a plugin instance that has missing dependencies (they are not used, but the plugin can start).

At runtime that plugin will check if the required dependencies are present and depending on that it will load those specific fields.

Possible solutions I thought of:
1) Virtually create the missing classes + packages and try again using ASM. But I don't really know how to do this.

Regards,
Maxim

Why should you care the fields while missing dependencies?

If it happen, the class should never have an instance at runtime. I don't think JRE will allows to create instance of object with missing class for it's field.

It might mean something if you read getDeclaredMethods.

ASM / BCEL is a good direction to go, but not virtually create the missing classes (as you will not know who they are). You are use them to read/parse the "class file" to decode it signature (ie getDeclaredFields without using classloader).

First of all make sure, that your target plugin is loaded before your plugin: You could force it to load, before your plugin, by adding this line to your plugin.yml file:

softdepend: [Pluginname]

Where the Pluginname is your reflection target plugin. Secondly, you should only get the fields, you need from this plugin, not listing every field, but if you would like to get it's all fields, than just decompile it's code and make a custom field getter method:

public ArrayList<Field> getFields(Class cl,String... analyze){
    ArrayList<Field> fields=new ArrayList<Field>();
    for (String f:analyze){
        try{
            Field field=cl.getDeclaredField(f);
            field.setAccessible(true);
            fields.add(field);
        } catch (Throwable err){
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM