简体   繁体   English

如何将泛型类型的类传递给Java中的方法?

[英]How to deliver the class of a generic type to a method in Java?

I want to implement a class that instantiates generic types. 我想实现一个实例化泛型类型的类。

public class DisjointSet<T extends Set<E>, E> {

    private final Class<T> setType;

    public DisjointSet(Class<T> setClass) {
        this.setType = setClass;
    }

    public void doSomething(E Element) {
        T set = setClass.newInstance();
        set.add(element);
    }
}

I tried instantiating the class like this: 我试图像这样实例化该类:

DisjointSet<HashSet<Integer>, Integer> disjointSet = new DisjointSet<>(HashSet<Integer>.class);

However using .class on a generic type does not seem to be allowed. 但是,似乎不允许在通用类型上使用.class How would I correctly pass the required Class of a generic type to the constructor? 我如何正确地将所需的泛型类型的Class传递给构造函数?

Not sure it is good to expose the inner set type (Hash versus other) in the parameterized type. 不能确定在参数化类型中公开内部集合类型(哈希与其他)。 Actually due to type erasure you can't instantiate parameterised types directly, but you can pass in a factory, 实际上,由于类型擦除,您无法直接实例化参数化类型,但可以在工厂中传递,

package langGenerics;

import java.util.HashSet;
import java.util.Set;

public class UseGenerics {
  public static void main(String[] args) {
    SetFactory<Integer> setFactory = HashSet::new;
    DisjointSet<Integer> disjointSet = new DisjointSet<>(setFactory);
    disjointSet.doSomething( 123 );
  }
}

interface SetFactory<T> { Set<T> get(); }

class DisjointSet<T> {
  private SetFactory<T> setFactory;
  public DisjointSet(SetFactory<T> setFactory) {
    this.setFactory = setFactory;
  }
  public void doSomething(T item) {
      Set<T> set = setFactory.get();
      set.add(item);
  }
}

If you really want to init your own set storage, then I suggest you to pass Supplier to your constructor: 如果您确实要初始化自己的集合存储,那么建议您将Supplier传递给构造函数:

public static class DisjointSet<T extends Set<E>, E> {
    T set;
    public DisjointSet(Supplier<T> supplier) {
        set = supplier.get();
    }

    public void doSomething(E element) {
        set.add(element);
    }
}

Then use it: 然后使用它:

DisjointSet<HashSet<Integer>, Integer> set = new DisjointSet<>(HashSet::new);

if this is what you wanted, 如果这是您想要的,

public class DisjointSet<T extends Set<E>, E> {

    private final Class<T> setType;

    public DisjointSet(Class<T> setClass) {
        this.setType = setClass;
    }

    public static void main(String[] args) {
        DisjointSet<HashSet<Integer>, Integer> disjointSet = new DisjointSet(new HashSet<Integer>().getClass());
    }
}

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

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