Class name.class class name.this

Other blog posts:

Class name.class class name.this detailed

 

in conclusion: 

  • When in the inner class of a class, if you need to access the methods or member fields of the outer class, if you use the this. member field (there is no difference from the inner class.this. member field), the domain of the inner class is obviously called, if When we want to access the domain of an external class, we must use the external class.this. member domain.
  • Passing new class name() or class name.this has the same effect.

 

Class name.class Class name.this test:

package com.company.test;

import java.lang.reflect.Method;

public class TestA {
	public void tn() {
		System.out.println("外部类tn");
	}

	String str = "123";

	Thread thread = new Thread() {
		public void tn() {
			System.out.println("inner tn");
		}

		public void run() {
			System.out.println("内部类run");
			// 调用外部类的tn方法
			TestA.this.tn();
			// 调用内部类的tn方法
			this.tn();
			// 传递 new TestA() 或 TestA.this 效果等同
			test1(new TestA());
			test2(TestA.this);
			try {
				test3(TestA.class);
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}

			// 反射测试
			try {
				Class calss = Class.forName("com.jiuqi.test.TestA");
				TestA q = (TestA) calss.newInstance();
				System.out.println(" 反射测试 ==> " + q.str);
			} catch (ClassNotFoundException e1) {
				e1.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	};

	public static void main(String aaa[]) {
		new TestA().thread.start();
	}

	protected void test3(Class<TestA> class1) throws InstantiationException, IllegalAccessException {
		TestA a = class1.newInstance();
		System.out.println("测试传参: 类.calss ==> " + a.str);
		Method[] methods = class1.getMethods();
		System.out.println("↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
		if (null != methods) {
			for (Method method : methods) {
				// System.out.println(method.getName());
			}
			System.out.println("测试反射");
		}
		System.out.println("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
	}

	protected void test1(TestA testA) {
		System.out.println("测试传参: new TestA() ==> " + testA.str);
	}

	protected void test2(TestA testA) {
		System.out.println("测试传参: TestA.this  ==> " + testA.str);
	}
}

Print result:

内部类run
外部类tn
inner tn
测试传参: new TestA() ==> 123
测试传参: TestA.this  ==> 123
测试传参: 类.calss ==> 123
↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
测试反射
↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
 反射测试 ==> 123

 

Guess you like

Origin blog.csdn.net/xiangwang2016/article/details/96439553