zoukankan      html  css  js  c++  java
  • 反射(创建运行时类的对象)

     1 package reflection;
     2 
     3 import java.lang.reflect.Constructor;
     4 import java.lang.reflect.Field;
     5 import java.lang.reflect.Method;
     6 
     7 // 获得类的信息
     8 public class Test08 {
     9     public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
    10         Class c1 = Class.forName("reflection.user");
    11 
    12         // 获得类的名字
    13         System.out.println(c1.getName()); // 获得包名+类名
    14         System.out.println(c1.getSimpleName()); // 直接得到类名
    15         
    16         // 获得类的属性
    17        /* Field[] fields = c1.getFields();
    18         for (Field field:fields) {
    19             System.out.println(field); // 啥也没输出,只能找到public的属性
    20         }*/
    21 
    22         Field[] fields = c1.getDeclaredFields(); // 找到全部的属性
    23         for (Field field:fields) {
    24             System.out.println(field);
    25         }
    26 
    27         // 获得指定属性的值
    28         Field name = c1.getDeclaredField("name");
    29         System.out.println(name);
    30 
    31         // 获得类的方法
    32         Method[] methods = c1.getMethods(); // 获得本类及父类的public方法
    33 
    34         Method[] declaredMethods = c1.getDeclaredMethods(); // 获取本类的所有方法
    35 
    36         // 获得指定类的方法
    37         c1.getMethod("getname",null);
    38 
    39         // 获取类的构造器
    40         Constructor[] constructors = c1.getConstructors();
    41 
    42         // 获得指定的构造器
    43         c1.getDeclaredConstructor(String.class,int.class,int.class);
    44 
    45 
    46 
    47     }
    48 }
  • 相关阅读:
    【原创】2013个人年终总结
    【原创】关于部门月会(二)
    【原创】关于部门月会(一)
    [转载]使用RoboCopy 命令
    ubuntu 16.04.3 安装完成后的一些初始化工作
    umbraco v7.6.4 surface controller not found 大深坑!
    ubuntu 及 postgredql 安装配置小坑摘录
    flex hack 记录
    C# 中的委托和事件
    OVER(PARTITION BY)函数介绍
  • 原文地址:https://www.cnblogs.com/YXBLOGXYY/p/14646635.html
Copyright © 2011-2022 走看看