クラスの反射
2223 ワード
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]);
}
}