How to get the Java compiler to tell me what type it has?

When I have a general Java function, for example:

<T> T choose(T a, T b) { }

and I call it from somewhere, how can I find out what type is inferred for T?

Edit: type inference occurs at compile time. So I ask, how do I get the compiler to tell me some information (the supposed type) that it has at compile time, but that does not make it in the .class file?

The only thing I can do is try to assign the result to variables of various types, for example:

// Compiles, so inferred type is at least Throwable.
Throwable foo = choose(new EOFException(), new FileNotFoundException());

// If this compiles, T must be Map or something that implements Map.
Map foo = choose(new HashMap(), new TreeMap());

But it is rather indirect. I would like the compiler to tell me what type it has for T, instead of having to play 20 questions.

+3
source share
3 answers

eclipse . Eclipse .

. , .

interface I {void foo();}
class C {}
class D extends C implements I { public void foo() {}}
class E extends C implements I { public void foo() {}}

java.util.Arrays.asList(new D(), new E()).get(0).foo();

? extends C, ? extends C & I, foo. , eclipse , ...

+3

, (c.f. Scala), .

Java erasure generics. , Java 7, .

0

Well, given your two examples, you don't need to expect a certain type as a result. The compiler will use the most typical generic type as "T", and if this "type" is an interface, then you will have instances of annoying classes implementing this interface (for your "foo" object).

0
source

Source: https://habr.com/ru/post/1724812/


All Articles