user968880
user968880

Reputation: 645

How to pass a java class as a reference at runtime?

I want to pass a class as an argument to a function. But I have the string variable which contains name of that class.

Upvotes: 2

Views: 401

Answers (5)

solendil
solendil

Reputation: 8468

This is the general method, you'll need to use a fully qualified class name.

myInstance.myMethod (Class.forName("fully.qualified.ClassName"));

Upvotes: 4

Sumit Singh
Sumit Singh

Reputation: 15886

Use static method of Class class

 yourMethod(other arguments,..., Class.forName("name of your class in string Formate.."));

this method return a Class class object for your class...

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258568

You can use reflection:

String className = "goo";
Class c = Class.forName(className);
foo(c);

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533492

Try

Class clazz = Class.forName(className);

Upvotes: 3

chance
chance

Reputation: 6487

try this:

 Class.forName("Foo")

but the corresponding class must be in the classpath.

Upvotes: 2

Related Questions