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

后端 未结 2 2031
[愿得一人]
[愿得一人] 2021-01-17 01:17

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

And equivalent syntax of Activator.CreateInstance() in jav

相关标签:
2条回答
  • 2021-01-17 01:36

    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 });
    
    0 讨论(0)
  • 2021-01-17 01:41

    You might achieve something like using Java reflection

    Class c - object.getClass();
    
    object.getClass().getConstructors()[0].newInstance(initargs);
    
    0 讨论(0)
提交回复
热议问题