Please see the code
public class TestMethodHandle {
class G {
void thinking(){
System.out.println("im G");
}
}
class F extends G {
@Override
void thinking(){
System.out.println("im F");
}
}
class S extends F {
@Override
void thinking(){
MethodType methodType = MethodType.methodType(void.class);
try {
Field impl_lookup = MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP");
impl_lookup.setAccessible(true);
MethodHandles.Lookup IMPL_LOOKUP = (MethodHandles.Lookup)impl_lookup.get(null);
MethodHandle mh = IMPL_LOOKUP.findSpecial(G.class , "thinking", methodType, G.class);//Please note here
mh.invoke(this);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
public static void main(String[] args) {
new TestMethodHandle().new S().thinking();
}
}
Run it
im G
If I change the code:
MethodHandle mh = IMPL_LOOKUP.findSpecial(G.class , "thinking", methodType, F.class);
// im G
or
MethodHandle mh = IMPL_LOOKUP.findSpecial(G.class , "thinking", methodType, S.class);
// im F
or
MethodHandle mh = IMPL_LOOKUP.findSpecial(F.class , "thinking", methodType, S.class);
// im F
I know it has the same effect as invokespecial, How does it implemented?
Aucun commentaire:
Enregistrer un commentaire