通配符,通用,setter和getter在java中 [英] wildcard, generic, setter and getter in java

查看:98
本文介绍了通配符,通用,setter和getter在java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class GenericClass< C> 
{
私人C值;

public C getValue(){return value; }

public void setValue(C value){this.value = value; }在我的代码中,我使用子类而不知道子类是什么,但我知道这两个子类子类是相同的类型:

  GenericClass<?> obj1 = ... //在这里有一个值
GenericClass<?> obj2 = ... //在这里有一个值

//我知道obj1是obj2的同一类型,但我不知道这种类型。
obj1.setValue(obj2.getValue());

最后一行产生一个编译错误:


类型GenericClass中的方法setValue(capture#11 of?)是
不适用于参数(capture#12 of?)


我该怎么做(类似于通配符......)?

解决由于 GenericClass<?> 不包含实际封闭类型的信息,编译器无法确保两个这样的类是兼容的。你应该使用一个具体的通用类型参数。如果你不知道具体的类型,你可能仍然可以通过例如实现两个类型参数的相同性。在一般方法中附上上述代码:

  public< T> void someMethod(){
GenericClass< T> obj1 = ... //在这里有一个值
GenericClass< T> obj2 = ... //在这里有一个值

obj1.setValue(obj2.getValue());





$ b如果这是不可能的,你可以作为最后的手段尝试明确的转换,或使用原始类型。这会将编译错误交易至未经检查的强制转换警告。


I've got a generic class with subclass.

public class GenericClass<C>
{
    private C value;

    public C getValue() { return value; }

    public void setValue(C value) { this.value = value; }
}

In my code I use subclasses without knowing what subclasses but I know this two subclasses are same type :

GenericClass<?> obj1 = ... // has a value here
GenericClass<?> obj2 = ... // has a value here

// I know that obj1 is the same type of obj2 but I don't know this type.
obj1.setValue(obj2.getValue());

The last line produce a compilation error which is :

The method setValue(capture#11-of ?) in the type GenericClass is not applicable for the arguments (capture#12-of ?)

How can I do that (something like casting a wildcard...) ?

解决方案

Since GenericClass<?> holds no information of the actual enclosed type, the compiler has no way to ensure that two such classes are compatible. You should use a concrete named generic type parameter. If you don't know the concrete type, you may still be able to enforce the sameness of the two type parameters by e.g. enclosing the above code in a generic method:

public <T> void someMethod() {
  GenericClass<T> obj1 = ... // has a value here
  GenericClass<T> obj2 = ... // has a value here

  obj1.setValue(obj2.getValue());
}

If this is not possible, you may as a last resort try explicit casts, or using raw types. This will trade the compilation error to unchecked cast warning(s).

这篇关于通配符,通用,setter和getter在java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆