简体   繁体   English

用Java动态扩展泛型类

[英]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. 我无法使用代理,因为我需要将获得的类添加到ClassLoader中。 I'm trying with javassist but I have no idea of how make it in the correct way. 我正在尝试使用javassist,但是我不知道如何以正确的方式进行制作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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