简体   繁体   English

检查Java中的通配符通用对象的类型

[英]Check type of wildcard generic object in Java

I'm writing a generic Pair class, that holds any two objects, (same or different types). 我正在编写一个通用的Pair类,它包含任意两个对象(相同或不同的类型)。 I am writing now a copy constructor, however, I'm getting some errors which I'm not able to solve. 我现在正在写一个复制构造函数,但是,我遇到了一些我无法解决的错误。 My code is below: 我的代码如下:

public class Pair<T1, T2> {
    // Instance Fields
    private T1 first;
    private T2 second;

    // Constructors
    public Pair() {}

    public Pair(Pair<?, ?> p) {
        first  = p.first;  // error here
        second = p.second; // error here
    }
}

Is there a way for me to check for the types of the ? 有没有办法让我检查一下? in the pair object using instanceof ? 在使用instanceof的pair对象中? If I cast p.first to T1 it works, but I want to make my class to be thorough and to handle any situation it might face, like if the user entered wrong object pair types, or other issues that might occur. 如果我将p.firstT1它可以工作,但我想让我的类彻底并处理它可能面临的任何情况,例如用户输入错误的对象对类型或可能发生的其他问题。

Another question is, is there a guideline or some kind of rules for using generics in Java? 另一个问题是,是否有在Java中使用泛型的指南或某种规则?

Try ? extends T1 试试? extends T1 ? extends T1 and ? extends T2 ? extends T1? extends T2 ? extends T2 - this will ensure that your objects are of the same type or a subtype. ? extends T2 - 这将确保您的对象属于同一类型或子类型。

public class Pair<T1, T2> {
    // Instance Fields
    private T1 first;
    private T2 second;

    // Constructors
    public Pair() {}

    public Pair(Pair<? extends T1, ? extends T2> p) {
        first  = p.first;
        second = p.second;
    }
}

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

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