首页 > 编程语言 > 详细

Java反射

时间:2018-09-01 22:45:59      阅读:168      评论:0      收藏:0      [点我收藏+]

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();
    }
}

 

Java反射

原文:https://www.cnblogs.com/zhwcs/p/9571703.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!