反射的一些基础操作

package Util;

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

public class ClassUtil {
    /**
     * 获输入一个对象得其类名
     * @param obj
     * @return
     */
    public static String getClassName(Object obj){
        return obj.getClass().getName();
    }
    
    public static void printMethods(Object obj){
        Class c=obj.getClass();
        //获得其类方法 与其父类方法
        Method[] methods=c.getMethods();
        
        //如果需要获得本类方法则使用    c.getDeclaredMethods();
        //如果需要获得构造方法则使用    c.getConstructors();
        System.out.println("该类含有方法为:");
        Class[] c2=null;
        int i=0;
        for(Method m:methods){
            i++;
            c2=null;
            System.out.print(i+"(");
            System.out.print("方法名:"+m.getName()+";");
            System.out.print("返回值类型:"+m.getReturnType()+";");
            c2=m.getParameterTypes();
            System.out.print("参数类型:");
            for(int j=0;j<c2.length;j++){
                System.out.print(j+" "+c2.getClass().getName()+" ");
            }
            System.out.println(")");
        }
    }
    /**
     * 获得一个类的所有成员变量
     * @param obj
     * @return
     */
     public Map getClassFields(Object obj){
         Map maps=new HashMap();
         Class c=obj.getClass();
         Field[] fields=c.getDeclaredFields();
         String fieldType="";
         String fieldName="";
         for(Field fieid:fields){
             fieldType=fieid.getType().getName();
             fieldName=fieid.getName();
             maps.put(fieldName, fieldType);
         }
        return maps;
     }
}

反射可以通过这一系列方法对一个不知道是什么的对象进行一系列操作比如万用的toString,比如构建万用的SQL语句(前提是数据库中的列名表名跟属性名对象名相同),比如执行万用的SQL之后是不是也可以返回一个对象而不是一堆需要重新处理的参数。

反射的应用讲究在不知道是什么的情况下进行操作,抽象化,通用化,利于构建框架,常用工具

posted @ 2017-05-22 15:16  酒皇  阅读(326)  评论(0编辑  收藏  举报