I developed the following sample class to better clarify my doubt.
package test;
import java.util.Arrays;
public class Main {
public static void main( String[] args ) {
new A( new StackDumper() ).exec( "test" );
new B( new GenericStackDumper() ).exec( "test" );
}
public interface I {
void test(String s);
}
public static class A {
private final I i;
public A( I i ) {
this.i = i;
}
public void exec(String b) {
i.test( b );
}
}
public static class StackDumper implements I {
public void test( String b ) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
System.out.println( Arrays.toString( elements ) );
}
}
public interface GenericI<T> {
void test(T t);
}
public static class B {
private final GenericI<String> i;
public B( GenericI<String> i ) {
this.i = i;
}
public void exec(String b) {
i.test( b );
}
}
public static class GenericStackDumper implements GenericI<String> {
@Override
public void test( String b ) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
System.out.println( Arrays.toString( elements ) );
}
}
}
As expected the first statement of in my main method prints something like:
[java.lang.Thread.getStackTrace(Thread.java:1552),
test.Main$StackDumper.test(Main.java:29),
test.Main$A.exec(Main.java:23),
test.Main.main(Main.java:7)]
Conversely the output of the second statement is a bit more surprising:
[java.lang.Thread.getStackTrace(Thread.java:1552),
test.Main$GenericStackDumper.test(Main.java:53),
test.Main$GenericStackDumper.test(Main.java:50),
test.Main$B.exec(Main.java:46),
test.main(Main.java:8)]
What I don't understand is why on this last call stack I see Main$GenericStackDumper.test printed twice, where one entry (line 53) is the actual invocation, while the other (line 50) corresponds to the line where the GenericStackDumper class is declared.
The only difference between the 2 implementations, and then the cause of this weird behaviour, is in the fact that in the second case I'm implementing a generified interface. However I couldn't find any justification for this in Java or JVM specs. Can anybody explain why this is happening?
Aucun commentaire:
Enregistrer un commentaire