Field.getGenericType() returns instance of java.lang.Class instead of Type

为君一笑 提交于 2019-12-12 15:08:26

问题


I'm having issues with proguard and some reflection stuff.

Myclass.java

package not.obfuscated
class MyClass {
    public List<InnerClass> childs;
}

InnerClass.java

package not.obfuscated
class InnerClass {
    //.somestuff
}

Inside proguard.cfg I have:

-keep class not.obfuscated.** {*;}

Inside another class I manage to get the "Field" instance for the MyClass.childs field and then try to get the getGenericType to determine which class is inside the List brackets (< InnerClass >)

For logging purposes I did the following Log.d code (field is the instance of Field representing MyClass.childs):

Log.d("FIELD", field.getName()+" generic type: "+ field.getGenericType()+ " class: "+ field.getGenericType().getClass().getName());

The output is following (2nd line):

As you see the field.getGenericType.toString() may be correct, but when I ask for the class it returns java.lang.Class. Indeed, a couple of line afterwards, when I do:

ParameterizedType listType = (ParameterizedType) field.getGenericType();

I receive a ClassCastException:

java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

I strongly believe this is due to proguard, but as far as I know of proguard I already excluded all the classes inside the not.obfuscated package. As last try I also inserted the line -keep class java.lang.List (obviously nothing happened).


回答1:


By default Proguard removes some of the type information: How do you stop Proguard from removing type parameters?

Adding the following line should fix the issue:

-keepattributes Signature

May be the whole magic line would work, i.e.:

-keepattributes Exceptions,InnerClasses,Signature,Deprecated,SourceFile,LineNumberTable,*Annotation*,EnclosingMethod 


来源:https://stackoverflow.com/questions/20072703/field-getgenerictype-returns-instance-of-java-lang-class-instead-of-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!