欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java通过反射获取属性字段名、值、数据类型

程序员文章站 2022-05-13 10:36:30
...
package cn.tzz.java.reflect;

import cn.tzz.aop.entity.Person;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.Test;

public class TestReflect {

	/** 方法--属性复制 */
	public void fieldCopy(Object source, Object target) throws Exception {
		Method[] methods = source.getClass().getDeclaredMethods();
		for (Method method : methods) {
			String methodName = method.getName();
			System.out.println(methodName);
			if (methodName.startsWith("get")) {
				Object value = method.invoke(source, new Object[0]);
				System.out.println(value);
				String setMethodName = methodName.replaceFirst("(get)", "set");
				Method setMethod = Person.class.getMethod(setMethodName,
						method.getReturnType());
				setMethod.invoke(target, value);
			}
		}
	}

	/** 属性字段名、值、数据类型 */
	public void getFields(Object object)  throws Exception {
		Field[] fields = object.getClass().getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			String classType = field.getType().toString();
			int lastIndex = classType.lastIndexOf(".");
			classType = classType.substring(lastIndex + 1);
			System.out.println("fieldName:" + field.getName() + ",type:"
					+ classType + ",value:" + field.get(object));
		}
	}

	@Test
	public void test() throws Exception {
		Person person = new Person();
		person.setId(1L);
		person.setName("AAA");
		Person person2 = new Person();
		fieldCopy(person, person2);
		getFields(person2);
	}
}