JAVA runtime class instance creation

 

Taken b station is still Silicon Valley video tutorials JAVA

        Class PersonC = Person.class;
        /*
        * Call newInstance conditions:
        * To provide a class corresponding to an empty argument constructor
        * 2 empty constructor parameters should be public access
        *
        *
        * */
        Object p = PersonC.newInstance();
        System.out.println(p);

By running the class, you can dynamically create different classes:

 int num = new Random().nextInt(3);
        String classPath = null;
        switch (num){
            case 0:
                classPath = "java.util.Data";
                break;
            case 1:
                classPath = "java.lang.Object";
                break;
            case 2:
                classPath = "com.LearnJava.reflect.Person";
                break;

        }
        try {
            System.out.println(getInstance(classPath));
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
    public static  Object getInstance (String classPath)throws Exception{
        Class cl = Class.forName(classPath);
        return cl.newInstance();
    }

 

Guess you like

Origin www.cnblogs.com/superxuezhazha/p/12356258.html