Java泛型父类取得子类的泛型参数T的Class类型
2019-03-19 19:56|来源: 网路
Java泛型父类取得子类的泛型参数T的Class类型,主要使用Class类的getGenericSuperclass方法,获取getActualTypeArguments[0]
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.junit.Test;
abstract class BaseDao {
public void getType() {
//Class clazz = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
Type t = getClass().getGenericSuperclass();
ParameterizedType p = (ParameterizedType) t ;
Class c = (Class) p.getActualTypeArguments()[0];
System.out.println(c.getName());//java.lang.String
}
}
public class SubDao extends BaseDao {
@Test
public void test1() {
getType();
}
}
转自:http://happyqing.iteye.com/blog/2228574
相关问答
在方法返回类型(如String,int,void或其他类)前面添加。 举个例子public int methodA(){ .... } 这样泛型参数T就可以在泛型方法内部使用了,去看Thinking in java的泛型章,很详细。 不过初学的话知道容器类后边加泛型参数就好了
对于您的Orchestrator泛型类型, INotifier#getNotifications(T)返回类型具有相同的形式参数应该是直截了当的,这一切都取决于您的notifier字段声明。 以下是Orchestrator类的开发示例: public class Orchestrator
{
private INotifier notifier;
public K getOrchestratedNotifications() {
...
您可以打开一个调用Type.GetGenericTypeDefinition 。 顺便说一句,如果您真的知道要创建List的实例,可以使用GetType(List(Of T))获取泛型类型定义。 You can get opened one calling Type.GetGenericTypeDefinition. BTW, if you really know that you're going to create an instance of List, you can get
...
为什么你不能在泛型类中使用(编辑 - 泛型)(在泛型类中使用该类型参数)静态方法 原因很简单:type参数不与类关联,而是与类的 实例关联。 即,你做不到 class Test {
public static void sayHello(T t) { // T for which instance?!
System.out.println("Hello");
}
}
为什么你可以在非泛型类中使用静态泛型方法? 你为什么不呢? 泛型方法采用类型参数,因此
...
你不应该(也不能)为此使用泛型。 相反,只需提供两种重载方法即可: public void myMethod(String value);
// and
public void myMethod(Provider value);
由于无论如何都需要进行一些不同的处理,所以这种方式实际上更简单。 You should not (and can not) use generics for this. Instead simply provide two overloaded method: publ
...
您可以将树更改为: class Tree {
public void insert(Node node) {
K key = node.getKey();
// do something...
}
// ... etc...
}
或者如果你想将它绑定到Node, class Tree2, K, T, V> {
public void insert(N
...
创建子类似乎是我将使用静态工厂方法的开销。 public class MyClass {
...
public static MyClass create(...)
...
}
Creating a subclass seems to be an overhead I would use a static factory method. public class MyClass {
...
...
extends表示“是或扩展”。 您的示例无法编译的原因是因为内部Parent类型是原始类型,它不是T extends Parent的有效替代。 “正确”类型如下所示: Parent>> ad infinitum。 显然这种类型是不可能宣布的。 一种解决方案是将其实例化为: Parent> parent = new Parent<>();
Parent> derived = parent.function();
这是有效的,因为编译器已经知道T
...
捕获单独委托中的取消订阅并在处置时执行: private Action _unsubscribeHandler;
public void AttachTo(T list) where T : INotifyCollectionChanged, ICollection
{
NotifyCollectionChangedEventHandler handler = delegate (object sender, NotifyCollectionChangedEventArg
...
9万+

被折叠的 条评论
为什么被折叠?



