|
假设有个类型CTest,我们可以直接创建它的实例
CTest t = CTest()
但是,如果构造函数CTest()被隐藏起来怎么办呢?
答案是反射:
CTest obj = getObject(CTest.class);
public <M> M getObject(Class<M> cls) {
M m = null;
Constructor<M> constructor = cls.getDeclaredConstructor(new Class[0]);
constructor.setAccessible(true);
try {
m = constructor.newInstance(new Object[0]);
} catch (Exception e) {
e.printStackTrace();
}
return m;
} |
|