Thinesh
Thinesh

Reputation: 37

Is there any equivalent syntax for C# Type.GetType() in java

Please let me know Is there any equivalent syntax for C# Type.GetType() in java.

And equivalent syntax of Activator.CreateInstance() in java.

Thanks.

Upvotes: 0

Views: 1989

Answers (2)

Jayamohan
Jayamohan

Reputation: 12924

Type.GetType() equivalent

Use Object.getClass() or instanceof

Activator.CreateInstance() equivalent

If a class has a no-argument constructor, then creating an object from its package-qualified class name is usually done using using Class.forName and Class.newInstance like below

 Class clazz = Class.forName("test.Demo");
 Demo demo = (Demo) clazz.newInstance();

If class dosent have no-argument constructor you must use Reflection like below

Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });

Upvotes: 2

fredcrs
fredcrs

Reputation: 3621

You might achieve something like using Java reflection

Class c - object.getClass();

object.getClass().getConstructors()[0].newInstance(initargs);

Upvotes: 0

Related Questions