zoukankan      html  css  js  c++  java
  • 反射

     
    package javaweb.reflect;
    
    public class Reflect {
    
        /**
         * @param args
         * @throws ClassNotFoundException 
         * 反射:加载类,获得类的字节码
         */
        public static void main(String[] args) throws ClassNotFoundException {
            //加载类方法1:
            Class c1 = Class.forName("javaweb.reflect.Person");
            //2
            Class c2 = new Person().getClass();
            //3
            Class c3 = Person.class;
        }
    
    }

    常用方法:

     1 //public
     2 Constructor getConstructor()
     3 Method getMethod()
     4 Field getField()
     5 //private
     6 Constructor getDeclaredConstructor()
     7 Method getDeclaredMethod()
     8 Field getDeclaredField()
     9 
    10 c.setAccessible(true);//暴力反射

     反射类的构造函数:

    1 public void test(){
    2         Class c = Class.forName("javaweb.reflect.Person");
    3         Constructor<T> cs = c.getConstructor(String.class);
    4         Person p = cs.newInstance("xxx");
    5     }

    反射类的方法:

    1 public void test() throws ClassNotFoundException {
    2             Person p = new Person();
    3             Class c = Class.forName("javaweb.reflect.Person");
    4             Method method = c.getMethod("funName", null);
    5             method.invoke(p,null);
    6         }

    反射类的字段:

     1 package javaweb.reflect;
     2 
     3 import java.lang.reflect.Field;
     4 
     5 public class Reflect {
     6 
     7     /**
     8      * @param args
     9      * @throws ClassNotFoundException 
    10      * 反射:加载类,获得类的字节码
    11      * @throws SecurityException 
    12      * @throws NoSuchFieldException 
    13      * @throws IllegalAccessException 
    14      * @throws IllegalArgumentException 
    15      */
    16     public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
    17         Person p = new Person();
    18         Class<?> c = Class.forName("javaweb.reflect.Person");
    19         Field f = c.getField("name");
    20         String name =(String) f.get(p);
    21         System.out.println(name);
    22         
    23         //打印出字段name的类型
    24         Class<?> type = f.getType();
    25         System.out.println(type);
    26     }
    27 }
  • 相关阅读:
    Redis数据类型有哪些?
    python---判断元素是否可用 is_displayed/is_enabled/is_selected
    pythone---获取文本链接,text/get_attribute/current_url/title
    python---清空 clear
    python---获取元素 CSS
    JDK安装及配hi环境
    python---获取元素 Xpath
    python---获取元素 id/name/class_name/link_text/partial选择器及注意事项
    python---数据类型----set集合和字典
    web搭建自动化环境
  • 原文地址:https://www.cnblogs.com/thinksasa/p/2791733.html
Copyright © 2011-2022 走看看