简体   繁体   English

可变类型的Java通用调用方法

[英]Java Generic Calling Method of Variable Type

I have a basic question about generics in Java. 我有一个关于Java泛型的基本问题。 I have a class X which is instantiated by another class T. In every class T which will be used has a method called as methodOfT(). 我有一个由另一个类T实例化的类X。在每个将要使用的类T中,都有一个称为methodOfT()的方法。 However, Java gives me compiler time error since it does not know obj and methodOfT(). 但是,Java给我编译器时间错误,因为它不知道obj和methodOfT()。

public class X<T>
{
     T obj;
     public void methodOfX()
     {
          obj.methodOfT();
     }  
}

In order to avoid this problem, what I did is I defined another class XSuper. 为了避免这个问题,我要做的是定义另一个类XSuper。 And every class now which wants to instantiate X will extend this XSuper class. 现在,每个要实例化X的类都将扩展此XSuper类。 This removes the compile time error and allows me to achieve what I want. 这消除了编译时错误,并使我能够实现自己想要的。

public abstract class XSuper
{
    public abstract void methodOfT();
}

public class UserOfX extends XSuper
{
    X<UserOfX> objX = new X<UserOfX>();
    public void methodOfT() 
    {
    }
}

However, I want to know the cleaner way of doing this thing. 但是,我想知道做此事的更干净的方法。 Since I want to derive class UserOfX from another Class. 由于我想从另一个类派生类UserOfX。 Another Problem is that I want to define methodOfT() method as - 另一个问题是我想将methodOfT()方法定义为-

public methodOfT(T objOfT)
{
}

In this case, the above solution fails. 在这种情况下,上述解决方案将失败。 Could someone help. 有人可以帮忙。

public class X<T>
{
     T obj;
     public void methodOfX()
     {
          obj.methodOfT();
     }  
}

The compiler doesn't know what T is so it is evaluated as Object. 编译器不知道T是什么,因此将其评估为Object。 Object does not have a methodOfT method, so compilation fails. 对象没有methodOfT方法,因此编译失败。 Here's how to solve that: 解决方法如下:

public interface SomeInterface{
    void methodOfT();
}
public class X<T extends SomeInterface>
{
     T obj;
     public void methodOfX()
     {
          obj.methodOfT();
     }  
}

In this case, the compiler knows that the supplied T will implement the interface SomeInterface and hence have the method methodOfT . 在这种情况下,编译器知道所提供的T将实现SomeInterface接口,因此具有methodOfT方法。 (You can also use classes instead of interfaces, but that's less elegant) (您也可以使用类而不是接口,但这不太好用)

Given your additional requirements, we're going t have to change this code some more: 考虑到您的其他要求,我们无需再更改此代码:

public interface SomeInterface<X>{
    void methodOfT(X object);
}
public class X<T1, T2 extends SomeInterface<T1>>
{
     T1 obj1;
     T2 obj2;
     public void methodOfX()
     {
          obj2.methodOfT(obj1);
     }  
}

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

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