Is it possible in java to create 'blank' instance of class without no-arg constructor using reflection?

后端 未结 5 1227
轻奢々
轻奢々 2020-12-08 19:57

I have a class which has not default constructor. And I need a way to get \'blank\' instance of this class. \'blank\' means that after instantiation all class fields should

5条回答
  •  独厮守ぢ
    2020-12-08 20:02

    Having Class instance provided as variable clazz:

    ReflectionFactory rf = ReflectionFactory.getReflectionFactory();
    Constructor objDef = parent.getDeclaredConstructor();
    Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef);
    clazz.cast(intConstr.newInstance());
    

    as described in http://www.javaspecialists.eu/archive/Issue175.html

提交回复
热议问题