通过反射动态获取抽象类实现,调用实现类中方法,JAVA通过反射动态获取接口所有实现类并实例化,Spring用map接收注入实现类

通过Bean名称或类名调用抽象类不同实现

一、通过类名调用

抽象类

public abstract class Animal {

	protected DbInfoService dbInfoService;
    protected ConfigUtil configUtil;

    public AbstractBackupRecovery(DbInfoService dbInfoService,
                                  ConfigUtil configUtil) {
        this.dbInfoService= dbInfoService;
        this.configUtil = configUtil;
    }

	abstract public void getMethodOne(String Id, String type);    

}

马类

public class Horse extends Animal {

	public Horse(DbInfoService dbInfoService, ConfigUtil configUtil) {
        super(dbInfoService, configUtil);
    }
	
	@Override
    public void getMethodOne(String Id, String type) {

    }

}

牛类

public class Cattle extends Animal {

	public Cattle(DbInfoService dbInfoService, ConfigUtil configUtil) {
        super(dbInfoService, configUtil);
    }
	
	@Override
    public void getMethodOne(String Id, String type) {

    }

}

抽象类中有空参构造时调用实现类方法

// 实现类路径
String classPath = "src.main.java.abstracts.impl.Horse";
// 获取实现类Class
Class<? extends Animal> otClass = (Class<? extends Animal>) Class.forName(classPath);
// 获取实例,用抽象类接收
Animal aClass = constructor.newInstance();
// 调用实现类中方法
aClass.getMethodOne(id, type);

抽象类中没有空参构造时调用实现类方法

// 实现类路径
String classPath = "src.main.java.abstracts.impl.Horse";
// 获取实现类Class
Class<? extends Animal> otClass = (Class<? extends Animal>) Class.forName(classPath);
// 获取有参构造
Constructor<? extends Animal> constructor = otClass.getConstructor(dbInfoService.class, configUtil.class);
// 获取实例,用抽象类接收
Animal aClass = constructor.newInstance(dbInfoService, configUtil);
// 调用实现类中方法
aClass.getMethodOne(id, type);

二、通过Bean名称调用

马类

@Component("HorseA")
public class Horse extends Animal {

	public Horse(DbInfoService dbInfoService, ConfigUtil configUtil) {
        super(dbInfoService, configUtil);
    }
	
	@Override
    public void getMethodOne(String Id, String type) {

    }

}

牛类

@Component("CattleA")
public class Cattle extends Animal {

	public Cattle(DbInfoService dbInfoService, ConfigUtil configUtil) {
        super(dbInfoService, configUtil);
    }
	
	@Override
    public void getMethodOne(String Id, String type) {

    }

}

实现类方法

//注入Animal所有实现 bean map
//map -> key 代表bean名称,value 代表bean实例
@Autowired
private Map<String,Animal> map;

Animal aClass = map.get("CattleA");
aClass.getMethodOne(id, type);

参考资料:
JAVA泛型知识<? extends T> 和 <? super T> 是Java泛型中的“通配符(Wildcards)” 和 “边界(Bounds)”的概念

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值