在 Java 中动态扩展泛型类 [英] Extend a generic class dynamically in Java
本文介绍了在 Java 中动态扩展泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在运行时扩展一个具有通用签名的类.
I need to extend on runtime a class with a generic signature.
比如要扩展的类是:
public class A<T> {}
我需要动态获取:
public class B extends A<String> {}
我无法使用Proxy,因为我需要将获取的类添加到ClassLoader.我正在尝试使用 javassist,但我不知道如何以正确的方式制作它.
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;
...
}
}
}
这篇关于在 Java 中动态扩展泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文