简体   繁体   English

分配Class <>类型的变量以在Java中实现接口

[英]Assigning variable of Class<> Type implementing an interface in Java

I want to create a variable of type Class , which implements some interface. 我想创建一个Class类型的变量,该变量实现一些接口。

Like: 喜欢:

Class<List<String>> b = ArrayList.class;

But when i try something like this, it complains about incompatible types, since the generics is filled with the concrete class. 但是当我尝试这样的事情时,它抱怨类型不兼容,因为泛型已被具体类填充。

Is there a way to do this? 有没有办法做到这一点?

I want to do this to be type safe further down the road. 我想这样做是为了确保以后的输入更加安全。 I know that it will work when i don't care about type safety, but if i could, I would rather do it in a type safe manner. 我知道当我不关心类型安全性时它会起作用,但是如果可以的话,我宁愿以类型安全的方式来做。

You can actually use Class<List<String>> b = (Class)ArrayList.class; 您实际上可以使用Class<List<String>> b = (Class)ArrayList.class; . It compiles, doesn't throw an exception and gives type safety. 它可以编译,不引发异常并提供类型安全性。

The reason you can't just use Class<List<String>> b = ArrayList.class; 您不能只使用Class<List<String>> b = ArrayList.class; is because ArrayList.class isn't a Class<List<String>> type, but rather a primitive class type. 是因为ArrayList.class不是Class<List<String>>类型,而是一个原始class型。 Casting it to Class removes the primitive and wildcard. 将其强制转换为Class会删除基元和通配符。

You get a type error here Class<List<String>> b = ArrayList.class; 您在这里得到类型错误Class<List<String>> b = ArrayList.class; 'couse ArrayList.class is not Class>. '因为ArrayList.class不是Class>。 Why? 为什么? Let's see, Think about lists, in their implementatios they look like 我们来看一下清单,在实现中看起来像

public interface List<T> ...

So, when you create a List, you MUST tell her wich is his type inside, for example: 因此,当您创建列表时,必须告诉她他的内心是他的类型,例如:

List<String> list1;
List<Integer> list2;

the original error is similar to: 原始错误类似于:

List<String> list1 = new String("Hi");
List<Integer> list2 = new Integer(5);

The correct way, is telling both types, that creates a new concrete type: 正确的方法是告诉这两种类型,从而创建新的具体类型:

List<String> list1 = new ArrayList<String>();
List<Integer> list2 = new ArrayList<Integer>();

list1 and list2, don't have the same type, although they both are List. 尽管list1和list2均为List,但它们的类型不同。

Finally, for your class "Class", the correct way is to do something like this: 最后,对于您的类“ Class”,正确的方法是执行以下操作:

import java.util.ArrayList;
import java.util.List;

public class Class<T> {

    private T v;

    public Class(T t){
        this.v = t;
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Class<List<String>> a = new Class<List<String>>(list);
    }

}

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

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