直播app开发,利用MethodHandle实现super关键字功能
Java版(仅jdk1.7+)
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Field;
public class JavaMethodHandleHelper {
static MethodHandles.Lookup lookup = MethodHandles.lookup();
static {
try {
Field allowedModes = MethodHandles.Lookup.class.getDeclaredField("allowedModes");
allowedModes.setAccessible(true);
allowedModes.set(lookup, -1);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object callSuperMethod(Object object, String name, String descriptor, Object... params) {
try {
return lookup.findSpecial(
object.getClass().getSuperclass(),
name,
MethodType.fromMethodDescriptorString(descriptor, null),
object.getClass()).
bindTo(object).
invokeWithArguments(params);
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
}
测试
public class ExampleUnitTest {
class A {
protected void onCreate() {
System.out.println("call A onCreate()");
}
}
class B extends A {
@Override
public void onCreate() {
JavaMethodHandleHelper.callSuperMethod(this,"onCreate","()V");
System.out.println("call B onCreate()");
}
}
@Test
public void testMethodHandle() {
new B().onCreate();
}
}
以上就是 直播app开发,利用MethodHandle实现super关键字功能,更多内容欢迎关注之后的文章
标签:java,app,class,MethodHandle,onCreate,super,public From: https://www.cnblogs.com/yunbaomengnan/p/16869607.html