zoukankan      html  css  js  c++  java
  • 获得类的运行时结构

    获得类的运行时结构

    代码如下

    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    
    //获得类的信息
    public class Test08 {
        public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
            Class c1 = Class.forName("com.lu.reflection.User");
    
    //        User user = new User();
    //        c1 = user.getClass();
    
            //获得类的名字
            System.out.println(c1.getName());  //获得包名 + 类名
            System.out.println(c1.getSimpleName()); //获得类名
    
            //获得类的属性
            System.out.println("=====================");
            Field[] fields = c1.getFields();  //只能找到public
    
          fields = c1.getDeclaredFields(); //找到全部的属性
            for (Field field : fields) {
                System.out.println(field);
            }
    
          //获得指定属性的值
            Field name = c1.getDeclaredField("name");
            System.out.println(name);
    
    
            //获得类的方法
            System.out.println("=====================");
            Method[] methods = c1.getMethods(); //获得本类及其父类的全部public方法
            for (Method method : methods) {
                System.out.println("正常的:"+method);
            }
            methods = c1.getDeclaredMethods();  //获得本类的所有方法
            for (Method method : methods) {
                System.out.println("getDeclaredMethods:"+method);
            }
    
            //获得指定方法
            //重载,所以需要参数
            System.out.println("=====================");
            Method getName = c1.getMethod("getName", null);
            Method setName = c1.getMethod("setName", String.class);
            System.out.println(getName);
            System.out.println(setName);
    
            //获得指定的构造器
            System.out.println("=====================");
            Constructor[] constructors = c1.getConstructors(); //获得public方法
            for (Constructor constructor : constructors) {
                System.out.println(constructor);
            }
            constructors = c1.getDeclaredConstructors();    //获得本类的全部方法
            for (Constructor constructor : constructors) {
                System.out.println("#"+constructor);
            }
    
            //获得指定的构造器
            Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
            System.out.println("指定:"+declaredConstructor);
        }
    }
    
  • 相关阅读:
    求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。
    getchar函数
    计算机网络04-ip与子网划分
    计算机网络03-传输层、可靠数据传输、UDP与TCP
    计算机网络02-应用层(http、email、dns)
    游戏-图形学学习路线
    markDown 入门
    webpack 入门级 傻瓜式教学
    npm 切换 cnpm 切换淘宝镜像源
    vue 父组件在接收子组件的同时传递一个当前的数据
  • 原文地址:https://www.cnblogs.com/helloxiaolu/p/13330519.html
Copyright © 2011-2022 走看看