简体   繁体   English

通用方法调用混乱

[英]Generic method call confusion

I have created a function 我创建了一个函数

public <T> void someFunction(T object) {
    object.someMethod();
}

I have two classes which has same someMethod() function definition. 我有两个类具有相同的someMethod()函数定义。 I have to invoke the function by passing argument, the object of these two classes depends on the input provided. 我必须通过传递参数来调用函数,这两个类的对象取决于提供的输入。

Since T has no type bounds, the compiler can't know if that parameter would be replaced by a class that has a someMethod method. 由于T没有类型界限,所以编译器无法知道该参数是否将被具有someMethod方法的类替换。

You can add a type bound: 您可以添加类型绑定:

public <T extends HasSomeMethod> void someFunction(T object) {
    object.someMethod();
}

Where HasSomeMethod is an interface that contains the someMethod method, and the two classes that have someMethod implement that interface. HasSomeMethod是一个包含someMethod方法的接口,而两个具有someMethod类都实现了该接口。 (it will also work if HasSomeMethod is a super-class of your two classes, and it contains the someMethod method (either abstract or not). (如果HasSomeMethod是两个类的超类,并且还包含someMethod方法(无论是否抽象),它也将起作用。

EDIT : 编辑:

An example of wrapping PreparedStatement : 包装PreparedStatement的示例:

public class MyStatement implements HasSomeMethod
{
    PreparedStatement stmt;

    public MyStatement (PreparedStatement stmt) {
         this.stmt = stmt;
    }

    public void someMethod ()
    {
        stmt.someMethod ();
    }
}

Now if you have a PreparedStatement instance, you can write : 现在,如果您有PreparedStatement实例,则可以编写:

PreparedStatement ps = ...
MyStatement my = new MyStatement(ps);

and pass my to your someFunction method. 并将my传递给您的someFunction方法。

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

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