简体   繁体   中英

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. However, I want to put some objects in this list that are instantiated from subclasses of type Baz (for overridden behavior).

So far, this is simple enough -- polymorphism in a 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. Is this possible in 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 . Define your method like this:

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

Then implement it like this (in class Baz):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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