反射基础学习

 

 

package Fanshe;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Demo {
    public static void main(String[] args) throws Exception {
        Class clazz = Test.class;
        Object obj = test(clazz);
        // System.out.println(obj);
        invoke1(obj, "chaoba");
        field(clazz);
        // annon(clazz);
    }

 
    public static Object test(Class clazz) throws Exception {
        Constructor con = clazz.getConstructor(String.class);
       
        Object obj = con.newInstance("超霸");
        return obj;

    }

  
    public static void invoke1(Object obj, String fangfaming) throws Exception {
        Method[] ms = obj.getClass().getDeclaredMethods();// 获取本类方法。包括私有方法,不包含夫类方法
        ms = obj.getClass().getMethods();// 获取继承的夫类方法。私有方法不显示。 显示公用方法

        /*
         * for (Method method : ms) { if(fangfaming.equals(method.getName())) {
         * method.invoke(obj, null);
         * 
         * } //System.out.println(method); }
         */
        Method m = obj.getClass().getMethod(fangfaming, null); // 获取指定方法
        m.invoke(obj, null); 
    }


    public static void field(Class clazz) {
        Field[] fs = clazz.getDeclaredFields();
        // fs=clazz.getFields();
        for (Field field : fs) {
            System.out.println(field.getName());
        }
    }

}

 

posted @ 2017-05-23 18:55  暮雪超霸  阅读(159)  评论(0编辑  收藏  举报