Extend a generic class dynamically in Java

爱⌒轻易说出口 提交于 2020-01-07 05:34:31

问题


I need to extend on runtime a class with a generic signature.

For example, the class to be extended is:

public class A<T> {}

I need to get this dynamically:

public class B extends A<String> {}

I cannot use Proxy because I need to add the obtained class to the ClassLoader. I'm trying with javassist but I have no idea of how make it in the correct way.


回答1:


If you know type only at runtime, then you will have to use casting. Like:

 class TokenCounterMapper 
    extends Mapper<Object, Object, Object, Object>{
     public void map(Object key, Object value, Context context){
    if (value instanceOf String){    
String castedString = (String)value;
        ...
        }
        }
        }


来源:https://stackoverflow.com/questions/16894571/extend-a-generic-class-dynamically-in-java

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