Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can a Class.forName returns a Class<? extends MyAbstractClass>?

Tags:

java

generics

Let's say I have an abstract class MyAbstractClass:

public abstract class MyAbstractClass {
   public abstract SomeObject doSomething();
}

and I have some concrete implementations of this class, MyConcreteClass1 and MyConcreteClass2.

Let's say I read the class name of any of the concrete implementations from a file and then I want to create the object:

String concreteImplementationName = getConcreteImplementationName();
Class<?> klass = Class.forName(concreteImplementationName);

I get the Class and then using reflection I can instantiate an object.

Now, in this case I know that the concreteImplementationName will only contain the name of one of the implementations of MyAbstractClass. How can I convert klass to a Class<? extends MyAbstractClass>?

Class<? extends MyAbstractClass> x = // what do I need to do here?
like image 282
SK176H Avatar asked Mar 18 '15 04:03

SK176H


2 Answers

You can use Class.asSubclass to do this. It works similarly to a cast, but for a Class object.

c.asSubclass(T.class) will check that c is actually a subclass of T, and if so it will return a Class<? extends T>. Otherwise it will throw a ClassCastException.

So you want this:

Class<? extends MyAbstractClass> x = klass.asSubclass(MyAbstractClass.class);
like image 146
user253751 Avatar answered Oct 01 '22 14:10

user253751


Just add a cast. You can do this safely because you know it's a subtype of MyAbstractClass

public class Example {
    public static void main(String[] args) throws Exception {
        String concreteImplementationName = "com.example.Implementation";
        Class<? extends MyAbstractClass> x = (Class<? extends MyAbstractClass>) Class.forName(concreteImplementationName); // what do i need to do
    }
}

class Implementation extends MyAbstractClass {
}

class MyAbstractClass {
}
like image 38
Sotirios Delimanolis Avatar answered Oct 01 '22 14:10

Sotirios Delimanolis