JAVA | 39 - 反射机制 | 反射实例化对象

利用反射实现了程序解耦合的目的,同时程序的可扩展性也非常强。

无参构造

interface Fruit{
    void eat();
}
class Apple implements Fruit{
    public void eat(){
        System.out.println("eat apple");
    }
}
class Orange implements Fruit{
    public void eat(){
        System.out.println("eat orange");
    }
}
class Factory{
    public static Fruit getInstance(String className){
        Fruit fruit = null;
        try{
            fruit = (Fruit) Class.forName(className).newInstance();
        }catch (Exception e){}
        return fruit;
    }
}
public class Main {
    public static void main(String[] args) {
        Fruit fruitA = Factory.getInstance("Apple");
        Fruit fruitB = Factory.getInstance("Orange");
        fruitA.eat();
        fruitB.eat();
    }
}

有参构造

import java.lang.reflect.Constructor;

interface Fruit{
    void eat();
}
class Apple implements Fruit{
    private String name;
    private int price;
    public Apple(String name, int price){
        this.name = name;
        this.price = price;
    }
    public void eat(){
        System.out.println(this.name + " " + this.price);
    }
}
class Orange implements Fruit{
    private String name;
    private int price;
    public Orange(String name, int price){
        this.name = name;
        this.price = price;
    }
    public void eat(){
        System.out.println(this.name + " " + this.price);
    }
}
class Factory{
    public static Fruit getInstance(String className, int price){
        Fruit fruit = null;
        try{
            Class <?> cls = Class.forName(className);
            Constructor <?> con = cls.getConstructor(String.class, int.class);
            fruit = (Fruit) con.newInstance(className, price);
        }catch (Exception e){}
        return fruit;
    }
}
public class Main {
    public static void main(String[] args) {
        Fruit fruitA = Factory.getInstance("Apple",5);
        Fruit fruitB = Factory.getInstance("Orange",4);
        fruitA.eat();
        fruitB.eat();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值