0

all I have:

String desiredClass = "MyClass";

I want to instantize this class, but this name comes from this string. I know it can be done with:

Class.forName(desiredClass);

formula, but this also need the package path from this string (name.space.path.MyClass). I know it can be queried by .getPackage() - but again, it needs a direct class reference, not from a string. It looks a snake has bitten its end :)

7
  • 5
    It's not possible because you never have the information anywhere. If I ask you to give me the profile of 'Jeroen', I can't expect you to give me 'Jeroen Vannevel' because there are multiple Jeroens in the world. You'll require more specific information. Commented Aug 18, 2014 at 10:03
  • 1
    How do you obtain the desiredClass value? Commented Aug 18, 2014 at 10:03
  • @sp00m its in an XML setting. Commented Aug 18, 2014 at 10:04
  • 2
    You could use techniques listed in this question to obtain a list of classes, which you could search for your class. But you'd need to be prepared for more than one matching result. Commented Aug 18, 2014 at 10:04
  • 2
    Can't you add the package as well in that XML setting? Commented Aug 18, 2014 at 10:04

1 Answer 1

1

You need to know the package name before initializing the object. Without it you wouldn't be able to distinct two classes with the same name from two separate packages.

If you had two classes test1.MyClass and test2.MyClass which one should be chosen in your code:

String desiredClass = "MyClass";
Class.forName(desiredClass);

So You need to know the package name in advance and do something like:

String desiredClass = "test1.myClass";
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.