欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

反射(Reflection)

程序员文章站 2024-01-20 22:31:40
...

class A {
public void method() {
System.out.println("A's method is running.");;
}
}

class B {
public void method() {
System.out.println("B's method is running.");;
}
}

class Factory {
@SuppressWarnings("unchecked")
public static <T> T getInstance(String className) {
T instatnce = null;
try {
Class<?> c = Class.forName(className);
instatnce = (T) c.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return instatnce;
}

public static <T> T getInstance(Class<T> c) {
T instance = null;
try {
instance = c.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return instance;
}
}

class Main {
public static void main(String[] args) {
A a = Factory.getInstance("A");
a.method();
B b = Factory.getInstance(B.class);
b.method();
}
}
相关标签: C C++ C#