zoukankan      html  css  js  c++  java
  • 反射基础学习

     

    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());
            }
        }
    
    }
    一万年太久,只争朝夕!
  • 相关阅读:
    在类中声明常量
    PHPStudy配置虚拟主机配置域名步骤
    PHPStudy配置虚拟主机步骤
    2019年7月22日星期一,简单的总结一下
    简单的面向对象
    session和cookie
    Jquery 事件绑定 bind 与on 的区别
    php try catch用法
    include,include_once,require,require_once的区别
    require与 include区别
  • 原文地址:https://www.cnblogs.com/chaoba/p/6895537.html
Copyright © 2011-2022 走看看