H2ONaCl
H2ONaCl

Reputation: 11269

How to invoke methods of a generic type in Java?

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 makeString()
    {
        return "The range is from " + min.asString() + " to " + max.asString();
    }
}

Upvotes: 0

Views: 162

Answers (2)

Bozho
Bozho

Reputation: 597026

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> { .. }

Upvotes: 0

bezmax
bezmax

Reputation: 26122

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();
    }
}

Upvotes: 4

Related Questions