java 匿名内部类对象持有外部类对象的引用

转载自:https://www.jianshu.com/p/9335c15c43cf

/**
 * @author hgl
 * @data 2019年1月10日
 * @description 接口
 */
public interface TestInterface {

	public void innerMethod();
}
/**
 * @author hgl
 * @data 2019年1月10日
 * @description 
 */
public class TestClass {

	public TestClass(){
		TestInterface ti = new TestInterface(){

			@Override
			public void innerMethod() {
				classMethod();
			}
			
		};
		ti.innerMethod();
		Class clazz = ti.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for(Field field : fields){
			System.out.println(field.getName());
			try {
				//返回指定对象上此 Field 表示的字段的值
				System.out.println(field.get(ti));
			} catch (IllegalArgumentException | IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		Field declaredField;
		try {
		  // this$0是上面打印出来的(field.getName)变量的名称,所以这里就直接使用了
			declaredField = clazz.getDeclaredField("this$0");
			System.out.println("反射this$0:"+declaredField.get(ti));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public void classMethod(){
		System.out.println("匿名内部类调用了外部类方法");
	}
}

《java 匿名内部类对象持有外部类对象的引用》

    原文作者:jclih
    原文地址: https://blog.csdn.net/weixin_37885641/article/details/86233365
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞