Rn2dy
Rn2dy

Reputation: 4190

How can I use a string to find the class that has the same name with the string

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

Answers (3)

skaffman
skaffman

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

Adam
Adam

Reputation: 44949

Class myClass = Class.forName("package.MyClass");

Object instance = myClass.newInstance();

where package is the name of the package containing MyClass

Upvotes: 0

Codemwnci
Codemwnci

Reputation: 54914

Class.forName may do what you want, but you will need the full package path as well.

Upvotes: 0

Related Questions