工厂设计模式中的反射问题
程序员文章站
2022-03-09 20:30:26
...
package Reflect;
interface Imessage{
public void send();
}
class Netmessage implements Imessage{
@Override
public void send() {
System.out.println("Send Net Message.");
}
}
class CloudMessage implements Imessage{
@Override
public void send() {
System.out.println("Send Cloud Message.");
}
}
interface Service{
public void service();
}
class IService implements Service{
@Override
public void service() {
System.out.println("service");
}
}
class Factory{
private Factory(){};
public static <T> T getInstance(String className,Class<T> T) throws Exception {
T instance=null;
instance = (T) Class.forName(className).getDeclaredConstructor().newInstance();
return instance;
}
}
public class Reflect01 {
public static void main(String[] args) throws Exception{
Imessage msg=Factory.getInstance("Reflection.Reflect.NetMessage",Imessage.class);
IService msg1=Factory.getInstance("Reflect.CloudMessage",IService.class);
msg.send();
msg1.service();
}
}