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 :)

John Smith
  • 6,129
  • 12
  • 68
  • 123
  • 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. – Jeroen Vannevel Aug 18 '14 at 10:03
  • 1
    How do you obtain the `desiredClass` value? – sp00m Aug 18 '14 at 10:03
  • @sp00m its in an XML setting. – John Smith Aug 18 '14 at 10:04
  • @JeroenVannevel ohh, yes there is a point – John Smith Aug 18 '14 at 10:04
  • you can't get the packaging only with the name. – Héctor Aug 18 '14 at 10:04
  • 2
    You could use techniques listed in [this question](http://stackoverflow.com/questions/3222638/get-all-of-the-classes-in-the-classpath) 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. – Duncan Jones Aug 18 '14 at 10:04
  • 2
    Can't you add the package as well in that XML setting? – sp00m Aug 18 '14 at 10:04

1 Answers1

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";
Michał Schielmann
  • 1,372
  • 8
  • 17