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?
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);
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 {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With