`

java反射

    博客分类:
  • Java
 
阅读更多
反射在java中应用比较广泛,例如Spring,Struts2。。。
package com.dp.service;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ReflectService {
	
	/**
	 * 
	 * @param object
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String reflectMethod(Object object){
		Class c = object.getClass();
		Method[] methods = c.getMethods();
		Field[] fields = c.getFields();
		String cName = c.getName();
		String tableName = cName.substring(cName.lastIndexOf(".") + 1,
                cName.length());
		
		System.out.println(cName);
		System.out.println(tableName);
		
		Map<String,String> maps = new HashMap<String,String>();
		
		for(Method method:methods){
			String tempName = method.getName();
			if (tempName.indexOf("get")== -1||tempName.indexOf("getClass")!=-1) {
				continue;
			}
			String feildName = tempName.substring(tempName.indexOf("get")+3,tempName.length()).toLowerCase();
			try {
				maps.put(feildName, String.valueOf(method.invoke(object, null)));
				System.out.println(feildName + "=" + method.invoke(object, null));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics