Reputation: 4190
So, suppose I have a string str = "MyClass", now I want to use this str to find the MyClass so I can instantiate it, and use it.
Upvotes: 3
Views: 84
Reputation: 403551
Simple example:
MyClass obj = Class.forName("com.xyz.MyClass").newInstance();
This assumes the existence of a default constructor, and will throw various exceptions if the class cannot be found, or cannot be instantiated.
Upvotes: 5
Reputation: 44949
Class myClass = Class.forName("package.MyClass");
Object instance = myClass.newInstance();
where package is the name of the package containing MyClass
Upvotes: 0
Reputation: 54914
Class.forName may do what you want, but you will need the full package path as well.
Upvotes: 0