核心:工厂
package com.example;
public class Factory {
public static <T> T creatObject(Class<T> clazz) {
T t = null;
try {
t = (T) Class.forName(clazz.getName()).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return t;
}
}
测试
package com.example;
public class Demo {
public static void main(String[] args) {
Ipay aliPay = Factory.creatObject(AliPay.class);
aliPay.pay();
}
}
接口:假设有支付接口
package com.example;
public interface Ipay {
void pay();
}
类:实现接口
package com.example;
public class AliPay implements Ipay {
@Override
public void pay() {
System.out.println("阿里支付");
}
}
运行结果:阿里支付