简体   繁体   English

从对象创建实例的通用方法

[英]generic method to create an instance from an object

Is this a safe way to create an instance (assuming T has a accessible default constructor) ? 这是创建实例的安全方法(假设T具有可访问的默认构造函数)吗?

<T>
public T defaultObj(T obj) throws Exception {
    return (T) obj.getClass().newInstance();
}

Because of the type erasure, the above codes will generate an unchecked warning. 由于类型擦除,以上代码将生成未经检查的警告。 Is it possible to get rid of this warning other than @SuppressWarnings? 除@SuppressWarnings之外,是否可以消除此警告?

Many thanks in advance! 提前谢谢了!

Edit: Yes, I know if I could pass a class<T> type which would be much better. 编辑:是的,我知道是否可以传递class<T> type ,这会更好。 But let's just assume it is out of question for now. 但是,让我们假设暂时没有问题。

您可以将签名稍微更改为<T> T defaultObj(Class<T> obj) ,然后newInstance()将返回适当的对象。

Is it possible to get rid of this warning other than @SuppressWarnings? 除@SuppressWarnings之外,是否可以消除此警告?

You could constrain T to extend some interface that provides a factory method. 您可以约束T来扩展提供工厂方法的某些接口。

interface Newable<T>
{
    T getNewInstance();
}

<T extends Newable<T>> T defaultObj(T obj)
{
    return obj.getNewInstance();
}

example implementation: 示例实现:

class Foo implements Newable<Foo>
{
    @Override
    public Foo getNewInstance() {
        return new Foo();
    }
}

That's exactly what @SuppressWarnings is supposed to do: this code is safe (because calling getClass() on an object of type T actually yields Class<? extends T> ), but compiler cannot understand it (return value of getClass() is declared as Class<?> due to limitations of generics) and generates warning. 这正是@SuppressWarnings应该做的:此代码是安全的(因为在T类型的对象上调用getClass()实际上会产生Class<? extends T> ),但是编译器无法理解它(声明了getClass()返回值getClass()由于泛型的限制,其为Class<?> )并生成警告。

It's absolutely legal to use @SuppressWarnings in this case, and you shouldn't try to avoid using it. 在这种情况下使用@SuppressWarnings是绝对合法的,并且您不应该避免使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM