微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 在它的抽象超类中使用泛型类型的子类?

在我的代码中,a有以下抽象超类
public abstract class AbstractClass<Type extends A> {...}

和一些儿童班一样

public class ChildClassA extends AbstractClass<GenericTypeA> {...}

public class ChildClassB extends AbstractClass<GenericTypeB> {...}

我正在寻找一种优雅的方式,我可以通用的方式在抽象类中使用子类的泛型类型(GenericTypeA,GenericTypeB,…).

为了解决这个问题,我目前定义了这个方法

protected abstract Class<Type> getGenericTypeClass();

在我的抽象类中实现了该方法

@Override
protected Class<GenericType> getGenericTypeClass() {
    return GenericType.class;
}

在每个儿童班.

是否可以在我的抽象类中获取子类的泛型类型而不实现此帮助器方法

BR,

马库斯

解决方法

我认为这是可能的.我看到这被用在DAO模式和泛型中.例如
考虑课程:
public class A {}
public class B extends A {}

而你的通用类:

import java.lang.reflect.ParameterizedType;
  public abstract class Test<T extends A> {

     private Class<T> theType;

     public test()  {
        theType = (Class<T>) (
               (ParameterizedType) getClass().getGenericSuperclass())
              .getActualTypeArguments()[0];
     }

     // this method will always return the type that extends class "A"
     public Class<T> getTheType()   {
        return theType;
     }

     public void printType() {
        Class<T> clazz = getTheType();
        System.out.println(clazz);
     }
  }

你可以有一个类Test1,用类B扩展Test(它扩展了A)

public class Test1 extends Test<B>  {

     public static void main(String[] args) {
        Test1 t = new Test1();

        Class<B> clazz = t.getTheType();

        System.out.println(clazz); // will print 'class B'
        System.out.println(printType()); // will print 'class B'
     }
  }

原文地址:https://www.jb51.cc/java/121377.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐