无法从java中的类访问泛型变量

时间:2012-10-08 20:15:58

标签: java

class example{ 
    private int x=1;
    public int xreturned(){
    return x;
   }
}
class example2<N>{
    example2<N> variable;
    public int fun(){
        int x=variable.xreturned(); 
    }
}
class mainclass{
    public static void main(String[] args){
       example2<example>obj=new example2<example>();
       if(1.equals(obj.fun()))
       System.out.println("correct");
       return 0;
   }
}
在fun2函数变量的class2类中找不到类例子的xreturned()函数,我怎样才能找到它呢?现在你可能会问我应该怎么找到它?我想是有可能找到它作为obj有例子(示例类的类型)泛型..所以请告诉我如何使它找到它与最小的变化

2 个答案:

答案 0 :(得分:4)

在运行时,由于type erasure,无法确定提供了哪个类。在您的情况下,看起来N将始终是Example类型,因此您的类定义可能是

class Example2<N extends Example> 

这会使你的例子有效,但我怀疑它可能过于简化以突出一个点(或家庭作业)。

答案 1 :(得分:1)

除了David的回答和Anna的评论之外,这里还有完整的代码(已测试)

请注意我必须做的一些其他更改才能进行编译(请参阅说明中的注释)

class Example{ 
    private int x=1;
    public int xreturned(){
    return x;
   }
}
class Example2<N extends Example> { //as in David's answer
    N variable; //as in Anna's comment
    public int fun(){
        int x=variable.xreturned(); 
        return x;
    }
}
class Mainclass{
    public static void main(String[] args){
       Example2<Example>obj=new Example2<Example>();
       if(1 == obj.fun()) // 1 doesn't have an equals method
           System.out.println("correct"); //indentation added, it's a condition

       //return 0; <-- you can't return 0 from main, it's return type is void
   }
}