反射(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();
}
}
下一篇: 支持向量机核心内容