简体   繁体   English

如何在类定义的通用类型中捕获子类型?

[英]How can I capture a subtype within a generic type in a class definition?

I can't believe I cannot capture P without typing the class to a redundant 2-type class: 我不敢相信如果不将类输入到冗余的2型类就无法捕获P:

public class MyClass<T extends List<P>> {

   T getList(/**/){}
   P getRandomElement(){ /**/ }
}

Do I need, really, to define and instantiate MyClass as MyClass<String,ArrayList<String>> , couldn't it be inferred someway? 我是否真的需要将MyClass定义和实例化为MyClass<String,ArrayList<String>> ,所以不能以某种方式推断出来吗?

EDIT: What I mean is I see redundant having to define MyClass<P,T extends List<P>> because then I need to instantiate it always as MyClass<String,ArrayList<String>> , and carry String everywhere. 编辑:我的意思是我看到有必要定义MyClass<P,T extends List<P>>因为我需要始终将其实例化为MyClass<String,ArrayList<String>> ,并随处携带String。 It would be nice if the language allowed something like 如果语言允许这样的话会很好

MyClass<L extends List<P>> or similar. MyClass<L extends List<P>>或类似内容。 That way, MyClass<ArrayList<String>> would return an ArrayList<String> when executing getList() and an String when executing getRandomElement() , nicely. 这样一来, MyClass<ArrayList<String>>将返回ArrayList<String>上执行时getList()和一个String上执行时getRandomElement()很好。

If you really must have the exact type of List returned from getList , then you need the type parameter T as well as P . 如果确实必须具有从getList返回的List的确切类型,则需要类型参数TP

public class MyClass<P, T extends List<P>> {

This way you can have a MyClass<String, ArrayList<String>> whose getList method returns an ArrayList<String> and a getRandomElement method that returns a String . 这样,您可以拥有MyClass<String, ArrayList<String>>getList方法返回ArrayList<String>getRandomElement方法返回String

However, it is usually unnecessary to know the exact type of List . 但是,通常不必知道List的确切类型。 Usually, if you have a List , then it doesn't matter to the user of this class which kind of List is really is. 通常,如果您有一个List ,那么对于此类的用户而言,实际上哪种List并不重要。 In this case, you don't need the type parameter T , only P . 在这种情况下,您不需要类型参数T ,只需要P You can change your class to this: 您可以将班级更改为此:

public class MyClass<P> {
   List<P> getList(/**/){}
   P getRandomElement(){ /**/ }
}

Then you can have a MyClass<String> whose getList method returns an List<String> and a getRandomElement method that returns a String . 然后,您可以拥有一个MyClass<String>getList方法返回一个List<String> ,一个getRandomElement方法返回一个String

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

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