开发者

How to invoke methods of a generic type in Java?

开发者 https://www.devze.com 2023-03-20 20:36 出处:网络
In this example the asString() invocations do not compile.(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 m

In this example the asString() invocations do not compile. (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?

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

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

    String makeSt开发者_开发技巧ring()
    {
        return "The range is from " + min.asString() + " to " + max.asString();
    }
}


You need to provide an interface that has asString method defined, for example:

interface AsStringable {
    String asString();
}

Then define your class like this:

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.

And about your code: the compiler should know what you know - i.e. that T will always have a given method. Currently you tell it only that there is T which is any Object. If it is limited to subtypes of Foo which defines asString(), then use <T extends Foo>

public interface Foo {
    String asString();
}

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

精彩评论

暂无评论...
验证码 换一张
取 消