我想返回一个传入的Class对象的相同类型对象的实例.传入的类型可以是ANYTHING.有没有办法用Generics做到这一点?
澄清 - 我不希望方法的调用者不必转换为他们传入的对象的类
例如,
public Object<Class> getObject(Class class)
{
// Construct an instance of an object of type Class
return object;
}
// I want this:
MyClass myObj = getObject(MyClass.class);
// Not this (casting):
MyClass myObj = (MyClass)getObject(MyClass.class);
Run Code Online (Sandbox Code Playgroud)
Tho*_*mas 17
我假设您要创建该类的新实例.使用泛型(你不能调用new T())是不可能的,并且使用反射也是非常有限的.
反思方法可以是:
//class is a reserved word, so use clazz
public <T> T getObject(Class<T> clazz) {
try {
return clazz.newInstance();
}
catch( /*a multitude of exceptions that can be thrown by clazz.newInstance()*/ ) {
//handle exception
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这仅在类具有无参数构造函数时才有效.
但是,问题是为什么你需要它而不是只是打电话new WhatEverClassYouHave().
public <C> C getObject(Class<C> c) throws Exception
{
return c.newInstance();
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
static <C> C getObject(Class<C> c) throws Exception {
return c.newInstance();
}
static class Testing {
{System.out.println("Instantiated");}
void identify(){ System.out.println("Invoked"); }
}
public static void main(String args[]) throws Exception {
Testing t = getObject(Testing.class);
t.identify();
}
Run Code Online (Sandbox Code Playgroud)