java Method isSynthetic

先看代码:

package com.reflect;

import java.lang.reflect.Method;

import junit.framework.TestCase;

import static java.lang.System.out;

public class TestSynthetic extends TestCase {

	public void testSynthetic() {
		try {
			Method[] methods = User.class.getDeclaredMethods();
			for (Method method : methods) {
				out.println(method.toString() + ", " + method.isSynthetic());
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		}
	}

	class User {
		private int age;
		private String name;

		private User() {
		}

		private User(int age, String name) {
			this.age = age;
			this.name = name;
		}

		private int getAge() {
			return age;
		}

		private void setAge(int age) {
			this.age = age;
		}

		private String getName() {
			return name;
		}

		private void setName(String name) {
			this.name = name;
		}

	}
}

运行testSynthetic,输出:

private java.lang.String com.reflect.TestSynthetic$User.getName(), false
private void com.reflect.TestSynthetic$User.setName(java.lang.String), false
private int com.reflect.TestSynthetic$User.getAge(), false
private void com.reflect.TestSynthetic$User.setAge(int), false

修改测试代码:

package com.reflect;

import java.lang.reflect.Method;

import junit.framework.TestCase;

import static java.lang.System.out;

public class TestSynthetic extends TestCase {

	public void testSynthetic() {
		try {
			User user = new User();
			user.age = 1;
			Method[] methods = User.class.getDeclaredMethods();
			for (Method method : methods) {
				out.println(method.toString() + ", " + method.isSynthetic());
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		}
	}

	class User {
		private int age;
		private String name;

		private User() {
		}

		private User(int age, String name) {
			this.age = age;
			this.name = name;
		}

		private int getAge() {
			return age;
		}

		private void setAge(int age) {
			this.age = age;
		}

		private String getName() {
			return name;
		}

		private void setName(String name) {
			this.name = name;
		}

	}
}

运行:

private java.lang.String com.reflect.TestSynthetic$User.getName(), false
private void com.reflect.TestSynthetic$User.setName(java.lang.String), false
static void com.reflect.TestSynthetic$User.access$1(com.reflect.TestSynthetic$User,int), true
private int com.reflect.TestSynthetic$User.getAge(), false
private void com.reflect.TestSynthetic$User.setAge(int), false

发现增加了一个方法:

static void com.reflect.TestSynthetic$User.access$1(com.reflect.TestSynthetic$User,int), true

这是编译器为这个类增加的,因为User这个内部类,全部的变量和方法,都是private的,但是外部程序要去调用,所以编译器做了这个工作。

上面只是修改了测试代码,并没有修改User这个内部类,就可以增加User的方法。


你可能感兴趣的:(java Method isSynthetic)