mardi 17 novembre 2015

Dealing with `Array.length` in java reflection [duplicate]

This question already has an answer here:

This is a follow-up to this question.

I am writing a library where I want to look for a (public) field with a specific name on a specific class. I am doing so via reflection:

public static Field findField(Class<?> instance_c, String name) {
    return instance_c.getField(name);
}

Now the problem is the following:

Class<?> c = int[].class;
// int i = new int[2].length;
System.out.println(findField(c, "length")); // Throws an exception

This is documented behaviour:

Method java.lang.Class.getField(String name):

[snip]

If this Class object represents an array type, then this method does not find the length field of the array type.


Is there a way that I somehow can still use the functionality of java.lang.reflect.Field with Array#length? I could imagine a builtin or selfwritten Proxie that lets me keep the functionality of Field in this one special case.

If I should further explain what of Field I'm using especially, please leave a comment. The goal is to keep as much as possible.





Aucun commentaire:

Enregistrer un commentaire