0

I have a method with signature

<T extends AbstractClass> T method(Class<T> abstractClass)

and I cannot modify the signature.

Also I have a string with class name com.test.MyClass. Is it possible to create a class by class name to pass to my method?

Something like that

Class<? extends AbstractClass> clz = (Class<? extends AbstractClass>) Class.forName(classNameStr);
4
  • 2
    You can't actually create concrete instances of an abstract class; you'll need something derived from it Commented Dec 10, 2014 at 21:26
  • My class name is a concrete class. It's a name of class which extends abstract class. Commented Dec 10, 2014 at 21:26
  • 3
    @Robert The OP isn't asking how to create an instance of a class given the class name as a String. She is asking how to call the given method so it returns an object of the class for which she only has the class name as a String. That's my understanding anyway. Commented Dec 10, 2014 at 21:34
  • @Barbara You can do something like this: AbstractClass obj = method((Class<? extends AbstractClass>) Class.forName("com.test.MyClass")); Commented Dec 10, 2014 at 22:00

1 Answer 1

2

If you want a type safe dynamic class loading, the correct way is:

Class<? extends AbstractClass> clz =
    Class.forName(classNameStr).asSubclass(AbstractClass.class);

This does not generate “unchecked” warnings as it is checked at runtime in the asSubclass method and afterwards, e.g. calling newInstance an that Class is guaranteed to return an instance of AbstractClass.


So afterwards you can do

AbstractClass obj = method(clz);

Of course, you can inline the construct as

AbstractClass obj=method(Class.forName(classNameStr).asSubclass(AbstractClass.class));

but it should be obvious why I wouldn’t recommend it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.