Java如何避免将Class作为通用对象的参数传递

时间:2018-10-26 12:21:40

标签: java generics

我写了以下内容:

public class DataContainer<Data>{

    public DataContainer(Class<Data> clazz, String method) throws NoSuchMethodException, SecurityException{

        clazz.getMethod(method);

    }

}

所以我以这种方式创建对象:

new DataContainer<SomeClass>(SomeClass.class, "get");

但我希望它看起来更像:

public class DataContainer<Data>{

    public DataContainer(String method) throws NoSuchMethodException, SecurityException{

        Data.getMethod(method);

    }

}

构造调用应如下所示:

new DataContainer<SomeClass>("get");

在构造Data对象时,如何避免传递DataContainer类?我知道Data不能在运行时进行操作(new DataContainer<>("get");->那么什么是Data?),但是我听说有一些解决方案可以解决,但不幸的是,我似乎没有尚未用谷歌搜索。

这也是我的问题的简化版本,我们假设方法有效,公开且没有参数。

1 个答案:

答案 0 :(得分:4)

由于类型擦除,您实际上不可能使用代码的方式。

但是,某些常规信息会在运行时保留,即在可以进行反射时保留。一种这样的情况是类层次结构上的泛型,即您可以执行以下操作(我们经常这样做):

//Note that I used T instead of Data to reduce confusion
//Data looks a lot like an actual class name
public abstract class DataContainer<T>{
  public DataContainer(String method) throws NoSuchMethodException, SecurityException {
    Class<?> actualClass = getActualTypeForT();
    //use reflection to get the method from actualClass and call it
  }

  protected Class<?> getActualTypeForT() {
    //get the generic boundary here, for details check http://www.artima.com/weblogs/viewpost.jsp?thread=208860
  } 
} 

//A concrete subclass to provide the actual type of T for reflection, can be mostly empty
public class SomeClassContainer extends DataContainer<SomeClass> {
  //constructor etc.
}

对于类字段或参数,应该有类似的可能,尽管我没有对此进行测试。

相关问题