简体   繁体   English

Java中如何调用泛型类型的方法?

[英]How to invoke methods of a generic type in Java?

In this example the asString() invocations do not compile.在此示例中, asString()调用无法编译。 (Aside: Invoking toString() does compile but I need to customize.) How do I invoke asString, or any method, of a generic type, given that the method has in fact been provided for every possible T ? (旁白:调用toString()确实可以编译,但我需要自定义。)我如何调用泛型类型的 asString 或任何方法,因为实际上已经为每个可能的T提供了该方法?

class Range<T>
{
    private T min;
    private T max;

    Range(T min, T max)
    {
        this.min = min;
        this.max = max;
    }  

    String makeString()
    {
        return "The range is from " + min.asString() + " to " + max.asString();
    }
}

You need to provide an interface that has asString method defined, for example:您需要提供一个定义了asString方法的接口,例如:

interface AsStringable {
    String asString();
}

Then define your class like this:然后像这样定义您的 class :

class Range<T extends AsStringable>
{
    private T min;
    private T max;

    Range(T min, T max)
    {
        this.min = min;
        this.max = max;
    }  

    String makeString()
    {
        return "The range is from " + min.asString() + " to " + max.asString();
    }
}

In fact, you can customize toString() by overriding it in your class - no need for a new method.事实上,您可以通过在 class 中覆盖它来自定义toString() - 不需要新方法。

And about your code: the compiler should know what you know - ie that T will always have a given method.关于你的代码:编译器应该知道你知道什么——即T总是有一个给定的方法。 Currently you tell it only that there is T which is any Object .目前你只告诉它有T是任何Object If it is limited to subtypes of Foo which defines asString() , then use <T extends Foo>如果仅限于定义asString()Foo的子类型,则使用<T extends Foo>

public interface Foo {
    String asString();
}

public class Range<T extends Foo> { .. }

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

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