jay
jay

Reputation: 29

Calling a class having its name as a string

I have a string which specifies the name of the call. How can i call the particular class by using this string.am trying this in java. A function will return me a list of strings which are class names.now task is to make a call to a class by using this string.

Upvotes: 2

Views: 11084

Answers (4)

RoflcoptrException
RoflcoptrException

Reputation: 52247

You can do this using this code:

Class clazz = Class.forName(yourString);

As the class name you should use the full class name including packages. But you can't call a class. You can initialize a class and then call a method of this class.

http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#forName(java.lang.String

Upvotes: 8

Harry Joy
Harry Joy

Reputation: 59694

Learn reflection. By reflection you can get class by its name.

Upvotes: 1

Tommi
Tommi

Reputation: 8608

You can use Class.forName(className). See Java API.

Upvotes: 3

StKiller
StKiller

Reputation: 7951

public class FooBar
{
    public static void main(String[] args) throws ClassNotFoundException {
        Class test = Class.forName("FooBar");
    }
}

Upvotes: 2

Related Questions