java-实现具体类自动实例化

背景

controller中生成了多个new的对象,为了解耦,需要实现多个对象自动实例化,使用class forname,首先先改造下类的结构,具体操作如下

class A{
	public A(String c){
	}
}
改造为
class A{
	private String c;
	public A(){
	}
	public A setT(String c){
		this.c=c;
	}
}

验证class forname可用

改造后的类的关系如下图
java-实现具体类自动实例化_第1张图片

DLSYOnhookStrategy 代码

package sample.Core;
import sample.JFXUtils;
public class DLSYOnhookStrategy extends OnhookStrategy{
    public DLSYOnhookStrategy() {
      
    }
    @Override
    public void onhook() {
        System.out.println(222222);
    }
}

SHHDOnhookStrategy代码

package sample.Core;
import sample.JFXUtils;
public class CommonOnhookStrategyextends OnhookStrategy{
    public SHHDOnhookStrategy() {
        
    }
    @Override
    public void onhook() {
     System.out.println(111111);
    }
}

调用class.forname

    public static void main(String[] args) {
         String cName="DLSYOnhookStrategy";
        String cName1="sample.Core."+cName;
        try {
            Class<?> c = Class.forName(cName1);
            OnhookStrategy dd= (OnhookStrategy) c.newInstance();
            dd.onhook();

            Class<?> c1 = Class.forName("sample.Core.CommonOnhookStrategy");
            OnhookStrategy dd1= (OnhookStrategy) c1.newInstance();
            dd1.onhook();

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

输入结果

22222
11111111
Process finished with exit code 0

你可能感兴趣的:(java,jvm,开发语言)