クラスに存在するフィールド、メソッド名を取得する

package example;

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

/**
 * クラスに存在するフィールド及びメソッドを取得する
 * (親クラスから継承したフィールド、メソッドを含む)
 * 
 * @author D.Magata
 */
public class GetClassAttributes {

	/**
	 * メイン処理
	 */
	public static void main(String[] args){
		
		String targetClassName = "example.ClassChild";
		Class  targetClass     = null;

		try {
			targetClass = Class.forName(targetClassName);
		} catch (ClassNotFoundException e) {
			System.out.println("指定されたクラス("+targetClassName+")が存在しません。");
			System.exit(1);
		}

		System.out.println("【" + targetClassName + "のフィールド、及びGetter 】");
		System.out.println(" ----------------------+---------------------");
		System.out.println("  フィールド名         | Getter名");
		System.out.println(" ----------------------+---------------------");
		Map map = getFields(targetClass);
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			String fieldName  = (String)it.next();
			String methodName = (String)map.get(fieldName);
			fieldName  = fieldName + repeatString(" " , 20 - fieldName.length());
			System.out.println("  " + fieldName + " | " + methodName);
		}
	}
	
	/**
	 * クラスに存在するフィールド名、Getter名を取得する
	 * @param cls
	 * @return Map<フィールド名, Getter名>
	 */
	public static Map<String, String> getFields(Class cls){
		Map<String, String> fieldMap = new HashMap<String, String>();
		Field[] fields = cls.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			String fieldName = fields[i].getName();
			String getterName = getGetterName(cls, fieldName);
			fieldMap.put(fieldName, getterName);
		}
		Class parCls = cls.getSuperclass();
		if (parCls != null){
			Map<String, String> parFieldMap = getFields(parCls);
			Iterator it = parFieldMap.keySet().iterator();
			while (it.hasNext()){
				String fieldName  = (String)it.next();
				String methodName = (String)parFieldMap.get(fieldName);
				fieldMap.put(fieldName, methodName);
			}
		}
		return fieldMap;
	}

	/**
	 * クラスのフィールド名に対応するGetter名を取得する
	 * @param  cls
	 * @param  fieldName
	 * @return Getter名
	 */
	public static String getGetterName(Class cls, String fieldName){

		String methodName = null;
		String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);

		try {
			Method method = cls.getDeclaredMethod(getterName, new Class[]{});
			methodName = method.getName();
		} catch (Exception e) {	}

		return methodName;
	}
	

	/**
	 * 文字列を指定回数分繰り返した文字列を返す(結果整形用)
	 */
	public static String repeatString(String str, int cnt){
		String allString = "";
		for (int i = 0; i< cnt; i++){
			allString = allString + str;
		}
		return allString;
	}
}

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2009-06-11 (木) 00:48:49 (5431d)