BufBills
BufBills

Reputation: 8113

Java, type between object and method

Callable<Boolean> callable = new Callable<Boolean>() {
    public Boolean call() throws Exception {
        return true; // do something useful here
    }
};

Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder() =====>
        .retryIfResult(Predicates.<Boolean>isNull())   =====>
        .retryIfExceptionOfType(IOException.class)
        .retryIfRuntimeException()
        .withStopStrategy(StopStrategies.stopAfterAttempt(3))
        .build();
try {
    retryer.call(callable);
} catch (RetryException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

Qustion:

RetryerBuilder.<Boolean>newBuilder() this line.

Why we can put <Boolean> before a method?

this is a strange to me in Java.

can someone explain it for me thanks

Upvotes: 1

Views: 104

Answers (2)

Iłya Bursov
Iłya Bursov

Reputation: 24229

here is the thing, in java you can write method like this:

static <T> T method(T obj) {
    return obj;
}

which will mean that java will detect type T during compilation, so:

Integer r1 = method(new Integer(0));

will compile fine, but:

String r2 = method(new Integer(0));

will give you compilation error

now, imagine situation:

static <T> T test(); // implementation of such method is not important right now, usually it is some kind of "reflection magic"

static void method1(String s);
static void method1(Integer i);

when you're calling with known types, everything works fine:

String s = test();
Integer i = test();
method1("string");
method1(1);

but, what if you do like this:

method1(Foo.test());

which method will be called? java cannot decide and will give you compilation error, to resolve it you have to indicate type, like this

method1(Foo.<String>test());

So, answer to your question

Why we can put <Boolean> before a method?

We can put it to resolve ambiguity when java compiler cannot detect type.

Upvotes: 1

Jeremy
Jeremy

Reputation: 576

This is a so called generic method. Usually, the return type of generic method (in the example below, T test(T obj)) is determined by assignment, i.e. String foo = Foo.test("bar"). If you call a method without assigning its return value to a variable, you must resolve the generic inline.

class Foo {
    public static <T> T test(T obj) {
        return obj;
    }

    public static void main(String[] args) {
        String foo = Foo.test("foo");

        System.out.println(foo); // output: "foo"
        System.out.println(Foo.<String>test("Test")); // output: "Test"
        System.out.println(Foo.<Integer>test(16));    // output: "16"
    }
}

Upvotes: 2

Related Questions