简体   繁体   中英

How to convert a generic type to a concrete type in Java

Hi I am currently working on some legacy code that I have inherited and I need to convert one type to another type to end my refactoring. The problem I am having is that I have a object that returns a Class<AbstractSuperClass> but I need to convert it into a AbstractSuperClass //(concrete object although abstract)

What I tried to do was to use enum constant to represent concrete subclasses of an abstract class and then use the constants to instantiate objects. But all my attempts of casting have thus far failed.

If somebody could provide some pointers in the right direction for this situation it would be most helpful.

Your question is not entirely clear. It looks like you are trying to use enum constants to represent concrete subclasses of an abstract class, and you want to be able to use these constants to instantiate objects. This is possible:

public enum ConcreteClass {

    CONCRETE1(Concrete1.class),
    CONCRETE2(Concrete2.class);

    private final Class<? extends AbstractClass> clazz;

    private ConcreteClass(Class<? extends AbstractClass> clazz) {
        this.clazz = clazz;
    }

    public AbstractClass instantiate() throws InstantiationException, IllegalAccessException {
        return clazz.newInstance();
    }
}

With this you can do AbstractClass obj = ConcreteClass.CONCRETE2.instantiate(); . You will have to do it in a try block as those exceptions are checked exceptions.

Personally I don't like using reflection for this. I think using a Supplier<AbstractClass> is nicer (requires Java 8):

public enum ConcreteClass {

    CONCRETE1(Concrete1::new),
    CONCRETE2(Concrete2::new);

    private final Supplier<AbstractClass> supplier;

    private ConcreteClass(Supplier<AbstractClass> supplier) {
        this.supplier = supplier;
    }

    public AbstractClass instantiate(){
        return supplier.get();
    }
}

This approach doesn't use reflection, doesn't involve checked exceptions, and is more general as it can be used with classes that only have static factory methods and no public constructors.

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