https://www.sczyh30.com/posts/Java/java-reflection-1/#3、创建实例
Fruit.java
package com.wzh.reflection; public interface Fruit { public void eat() ; }
Apple.java
package com.wzh.reflection; class Apple implements Fruit { public Apple() {} public void eat() { System.out.println("吃苹果。"); }; }
Orange.java
package com.wzh.reflection; class Orange implements Fruit { public Orange() {} public void eat() { System.out.println("吃橘子。"); }; }
MyRun.java
package com.wzh.reflection; import java.lang.reflect.Constructor; class Factory { public static Fruit getInstance(String className) { Fruit fruit = null; try{ Class<?> clazz = Class.forName(className); Constructor<?> constructor = clazz.getConstructor(); Object obj = constructor.newInstance(); fruit = (Fruit)obj; } catch(Exception e) { e.printStackTrace(); } return fruit; } } public class MyRun { public static void main(String[] args) { Fruit fruit = Factory.getInstance("com.wzh.reflection.Orange") ; fruit.eat(); } }
原文:https://www.cnblogs.com/zhwcs/p/9571703.html