How to create objects from a class with private constructor?

前端 未结 6 1540
花落未央
花落未央 2021-01-14 00:39

I have a class Game that is my main class and a second class Card. Class Card hast its properties and constructor private, only function init is public. Function init checks

6条回答
  •  感情败类
    2021-01-14 00:53

    Class class = Class.forName("SomeClassName"); 
    Constructor constructor = class.getConstructors[0];
    constructor.setAccessible(true);
    

    To convert the privately declared constructor to the public one till program execution. Also, this concept is related to Reflection API.

    Object o = constructor.newInstance();
    if(o.equals(class)) {
        System.out.println("Object for \"SomeClassName\" has been created");
    }
    

提交回复
热议问题