简体   繁体   中英

Extend a generic class dynamically in Java

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.

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;
        ...
        }
        }
        }

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