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

类的反射

程序员文章站 2022-05-13 17:42:27
...
package com.funo.web_frame.test;

import java.lang.reflect.Field;

public class Engine 
{

	private String engineId;
	private String engineName;
	private String engineType;

	public static void main(String[] args) throws Exception
	{
//		 Engine3 m = new Engine3();
		 Engine m = new Engine();
		 m.engineId="dddd";
		 Engine.getNamesValues(m, "===================");
	}
            /**
	 * 获取对象 所以属性值与属性  在同一个类中 属性为private 可以获取
	 * 不同类中或者包中 private 属性值无法获取 
	 * @param o
	 * @param s
	 */
	public static void getNamesValues(Object o, String s)
	{
		Field[] f = o.getClass().getDeclaredFields();
		Object[] value = new Object[f.length];
		String name[] = new String[f.length];
		for (int i = 0; i < f.length; i++)
		{
			 name[i] = f[i].getName();
			 try
			 {
			   value[i] = f[i].get(o);
			 } catch (Exception e)
			 {
				 e.printStackTrace();
			 }
			 System.out.println("name:" + name[i]);
			 System.out.println("Value:" + value[i]);
		}
	}

}





===================通过类的 set get 方法获取==========================
    @SuppressWarnings("unchecked")
	public static void getNamesValues(Object o ,String s)  
	{
		System.out.println("****************"+s+"*****************");
		Field[] f = o.getClass().getDeclaredFields();
		Class classType = o.getClass();
		Object[] value = new Object[f.length];
		for (int i = 0; i < f.length; i++)
		{
			String fieldName = f[i].getName();
			String firstLetter = fieldName.substring(0, 1).toUpperCase();
			String getMethodName = "get" + firstLetter + fieldName.substring(1);
			Method getMethod;
			try
			{
				getMethod = classType.getMethod(getMethodName, new Class[] {});
				value[i] = getMethod.invoke(o, new Object[] {});
			} catch (Exception e)
			{
			}

			System.out.println(fieldName+" = "+value[i]);
		}
	}

 

上一篇: MySql_connection

下一篇: function