简体   繁体   English

使用Java反射和泛型:方法是否可以将实际类型指定为其返回值?

[英]Using Java reflection and generics: can a method specify an actual type as its return value?

I have a class that is maintaining a list of objects of type Baz. 我有一个维护Baz类型对象列表的类。 However, I want to put some objects in this list that are instantiated from subclasses of type Baz (for overridden behavior). 但是,我想在此列表中放置一些对象,这些对象是从Baz类型的子类实例化的(用于重写行为)。

So far, this is simple enough -- polymorphism in a List. 到目前为止,这很简单-List中的多态。 However, the class maintaining the list is itself abstract, and different implementations will require that different types be placed in the list. 但是,维护列表的类本身是抽象的,并且不同的实现将要求在列表中放置不同的类型。 Some abstract function getTypeToUse should specify the type of the element to insert into the list. 一些抽象函数getTypeToUse应该指定要插入列表中的元素的类型。 Is this possible in Java? 这在Java中可行吗?

Consider the following pseudocode: 考虑以下伪代码:

public abstract class Foo {
    public void Bar() {
        List<Baz> qux = new ArrayList<>();
        Type buzz = getTypeToUse();
        Baz fizz = new buzz();
        qux.add(fizz);
    }

    // The returned Type should be some subclass of Baz
    // It would be nice to enforce this, like <? extends Baz>
    public abstract Type getTypeToUse(); 
}

Thank you! 谢谢!

You could return a class object instead. 您可以改为返回一个类对象。 The class Class<T> implements the interface Type . Class<T>实现接口Type Define your method like this: 像这样定义您的方法:

public abstract Class<? extends Baz> getClassToUse();

Then implement it like this (in class Baz): 然后像这样实现它(在Baz类中):

@Override
public Class<? extends Baz> getClassToUse() {
   return Baz.class;
}

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

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