无法在Java中调用泛型对象的方法。

huangapple go评论100阅读模式
英文:

Can't call method of a Generic Object in Java

问题

import java.util.*;
class GenericClass<T> {
    ArrayList<T> list = new ArrayList<>();

    void add(T obj) {
        list.add(obj);
    }

    void callMethod() {
        list.get(0).display();
    }
}

class Test {
    public void display() {
        System.out.println("HELLO WORLD");
    }
}

class Main {
    public static void main(String... args) {
        GenericClass<Test> gen = new GenericClass<Test>();
        Test t = new Test();
        gen.add(t);
        gen.callMethod();
    }
}

你创建了这些简单的类。Test类对象被传递给add函数,但是我无法使用display方法。它会报错 - 无法找到符号display()

当我只打印对象时,我可以看到它打印出了正确的对象。
请帮忙,我对Java非常新。
谢谢。

英文:
 import java.util.*;
class GenericClass&lt;T&gt;{
	ArrayList&lt;T&gt; list = new ArrayList&lt;&gt;();

	void add(T obj){
		list.add(obj);
	}

	void callMethod(){
		list.get(0).display();
	}
}

class Test{
	public void display(){
		System.out.println(&quot;HELLO WORLD&quot;);
	}
}

class Main{
	public static void main(String... args){
		GenericClass&lt;Test&gt; gen = new GenericClass&lt;Test&gt;();
		Test t = new Test();
		gen.add(t);
		gen.callMethod();
	}
}

I have created these simple classes. The Test class object is passed to add function, but I can use the method display. It gives the error - Can't find symbol display()

When I just print the object, I can see that it it prints the correct object.
Please help, I'm very new to java.
Thank you

答案1

得分: 3

你必须将你的泛型类型声明为Test类的扩展,因为T,没有任何扩展,可以是任何类型,甚至可能没有display()方法。

class GenericClass<T extends Test>{
    ArrayList<T> list = new ArrayList<>();
    
    void add(T obj){
        list.add(obj);
    }
    
    void callMethod(){
        list.get(0).display();
    }
}

class Test{
    public void display(){
        System.out.println("HELLO WORLD");
    }
}
英文:

You have to declare your generic type as an extension of Test class, because T, without any extension, could be any type, even one which don't have a display() method.

class GenericClass&lt;T extends Test&gt;{
    ArrayList&lt;T&gt; list = new ArrayList&lt;&gt;();

    void add(T obj){
        list.add(obj);
    }

    void callMethod(){
        list.get(0).display();
    }
}

class Test{
    public void display(){
        System.out.println(&quot;HELLO WORLD&quot;);
    }
}

huangapple
  • 本文由 发表于 2020年8月2日 01:31:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63208155.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定