• java基础---反射得到属性方法及调用(1)


    --反射应用

    package com.part1;
    /**
     * 
     * @author pc
     *
     */
    public class Student {
        public int sid;
        public char sex;
        private String sname;
        private String password;
        private String cardno;
        private double money;
        
        public Student() {
        }
        public Student(int sid, String sname, String password, String cardno,
                double money) {
            this.sid = sid;
            this.sname = sname;
            this.password = password;
            this.cardno = cardno;
            this.money = money;
        }
        public int getSid() {
            return sid;
        }
        public void setSid(int sid) {
            this.sid = sid;
        }
        public String getSname() {
            return sname;
        }
        public void setSname(String sname) {
            this.sname = sname;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public String getCardno() {
            return cardno;
        }
        public void setCardno(String cardno) {
            this.cardno = cardno;
        }
        public double getMoney() {
            return money;
        }
        public void setMoney(double money) {
            this.money = money;
        }
        
        public char getSex() {
            return sex;
        }
        public void setSex(char sex) {
            this.sex = sex;
        }
        
        private void eat(String str){
            System.out.println("中午吃了一份:"+str);
        }
        
        @Override
        public String toString() {
            return "Student [cardno=" + cardno + ", money=" + money + ", password="
                    + password + ", sex=" + sex + ", sid=" + sid + ", sname="
                    + sname + "]";
        }
    
    }
    student
    package com.part1;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    /**
     * 1.获取Class对象,获取public属性和方法
     * @author pc
     *
     */
    public class Test {
        public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchFieldException, NoSuchMethodException {
            //1.获取Class对象
            //1.1 第一种获取Class对象方法:对象名.getClass()
            Student stu=new Student(1, "李震东", "123", "3201121990", 47.5);
            Class<Student> cla1=(Class<Student>) stu.getClass();
            System.out.println(cla1);
            
            //1.2 第二种获取Class对象的方法:类名.class;
            Class<Student> cla2=Student.class;
            System.out.println(cla2);
            
            //1.3 第三种获取Class对象的方法:
            Class<Student> cla3=(Class<Student>) Class.forName("com.part1.Student");
            System.out.println(cla3);
            
            //2.获取属性
            //2.1先获取所有public属性
            System.out.println("--------2.1先获取所有public属性---------");
            Field[] fields1=cla1.getFields();
            for (Field field : fields1) {
                System.out.println(field);
            }
            //2.2 获取某个属性
            System.out.println("---------2.2获取某个属性---------");
            Field field2 =cla2.getField("sex");
            System.out.println(field2);
            
            //3.获取方法
            //3.1 获取所有的public方法
            System.out.println("------3.1 获取所有的public方法------");
            Method[] methods=cla1.getMethods();
            for (Method method : methods) {
                System.out.println(method);
            }
            
            //3.2 获取某个public方法
            System.out.println("---------3.2 获取某个public方法---------");
            Method method2=cla2.getMethod("setSname", String.class);
            System.out.println(method2);
            
            
            
            
            
    
        }
    
    }
    Test得到属性和方法
    package com.part1;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    /**
     * 2.对于public修饰属性和方法操作:
     * 动态创建对象
     * 动态调用属性
     * 动态给属性赋值
     * 动态调用方法
     * @author pc
     *
     */
    public class Test2 {
        public static void main(String[] args) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
            //1.获取Class对象
            Class cla=Student.class;
            
            //2.动态创建对象(卧底身份)
            //2.1 通过无参构造创建对象
            Student stu1=(Student) cla.newInstance();
            System.out.println("通过无参构造创建对象动态创建对象:"+stu1);
            
            //2.2 通过有参数构造创建对象
            //2.2.1 获取有参数构造
            Constructor conn=cla.getConstructor(int.class,String.class,String.class,String.class,double.class);
            
            //2.2.2 通过有参数的构造方法创建对象
            Student stu2=(Student) conn.newInstance(1,"东东","123","3201121990",45.5);
            System.out.println("通过有参数构造创建对象:"+stu2);
            
            //3.动态调用属性并给属性赋值
            //3.1 动态调用属性
            Field sexField=cla.getField("sex");
            
            //3.2 动态给属性赋值
            sexField.set(stu1, '女');
            
            //3.3 动态获取属性值
            System.out.println("sex属性值为:"+sexField.get(stu1));
            
            //4.动态获取方法并动态调用方法
            //4.1 动态获取某个公共方法
            Method setMoneyMethod=cla.getMethod("setMoney", double.class);
            
            //4.2 动态调用方法(※)
            setMoneyMethod.invoke(stu1, 9999.99);
            System.out.println(stu1);
        }
    
    }
    Test 调用
    package com.part1;
    
    import java.lang.reflect.Field;
    
    /**
     * 3.操作私有的属性
     *
     */
    public class Test3 {
        public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InstantiationException {
            //1.获取Class对象
            Class cla=Class.forName("com.part1.Student");
    
            //2.通过反射的无参数的构造创建对象
            Student stu=(Student) cla.newInstance();
            
            //3.获取私有属性
            //3.1获取所有属性和访问修饰符无关
            System.out.println("----3.1获取所有私有属性------");
            Field[] fields=cla.getDeclaredFields();
            for (Field field : fields) {
                System.out.println(field);
            }
            //3.2获取某个属性和访问修饰符无关
            System.out.println("----3.2获取某个属性和访问修饰符无关------");
            Field moneyfield=cla.getDeclaredField("money");
            System.out.println(moneyfield);
            
            //3.3给属性解除私有权限
            moneyfield.setAccessible(true);
            
            //3.4 给私有属性赋值
            moneyfield.set(stu, 9999.99);
            
            //3.5 获取私有属性值
            System.out.println(moneyfield.get(stu));
                
                
        }
    
    }
    Test操作私有的属性
    package com.part1;
    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    /**
     * 4.操作私有方法并调用私有方法
     */
    public class Test4 {
        public static void main(String[] args) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
            //1.获取Class对象
            Class<Student> cla=Student.class;
            
            //2.通过Class对象反射创建Student对象
            Student stu=cla.newInstance();
            System.out.println(stu);
            
            //3.获取所有方法和访问修饰符无关
            System.out.println("-------获取所有方法和访问修饰符无关-----------");
            Method[] methods=cla.getDeclaredMethods();
            for (Method method : methods) {
                System.out.println(method);
            }
            
            //4.获取某个私有的方法
            Method eatMethod=cla.getDeclaredMethod("eat", String.class);
            System.out.println("获取某个私有方法:"+eatMethod);
            
            //5.解除私有方法权限
            eatMethod.setAccessible(true);
            
            //6.调用私有方法并传入实参
            System.out.println("----------调用私有方法----------");
            eatMethod.invoke(stu, "快餐");
     
        }
    
    }
    Test调用私有

     使用反射调用方法时执行效率比较 正常调用、安全检查调用、不执行安全检查调用

    package com.bdqn.service;
    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class Demo1 {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{
          //不执行安全检查比执行安全检查效率高4倍   test3用时-1288ms
          test3();
          //执行安全检查速度最慢        test2用时-4890ms
          test2();
          //效率是不执行安全检查的30倍,是执行安全检查的120倍    test1用时-413ms
          test1();
    }
    
     private static void test1(){
      Emp  emp=new Emp();
      long startTime=System.currentTimeMillis();
       for (int i = 0; i <1000000000L; i++) {
        emp.getEmpName();
       }
       
       long endTime=System.currentTimeMillis();
        System.out.println("test1用时"+(startTime-endTime)+"ms");
       
        
       
     }
     private static void test2() throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{
         Class<Emp> emp1=Emp.class;
         Emp emp=emp1.newInstance();
         Method method=emp1.getDeclaredMethod("getEmpName", null);
         long startTime=System.currentTimeMillis();
         for (int i = 0; i <1000000000L; i++) {
            method.invoke(emp, null);
         }
         long endTime=System.currentTimeMillis();
         System.out.println("test2用时"+(startTime-endTime)+"ms");
     }
     private static void test3()throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{
         Class<Emp> emp1=Emp.class;
          Emp emp=emp1.newInstance();
         Method method=emp1.getDeclaredMethod("getEmpName", null);
         //不需要执行访问检查
         method.setAccessible(true);
         long startTime=System.currentTimeMillis();
         for (int i = 0; i <1000000000L; i++) {
            method.invoke(emp, null);
         }
         long endTime=System.currentTimeMillis();
         System.out.println("test3用时"+(startTime-endTime)+"ms");
     }
    }
    compare

    package com.bjsxt.test;
    
    import java.lang.reflect.Method;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    import java.util.List;
    import java.util.Map;
    
    
    /**
     * 通过反射获取泛型信息
     * @author dell
     *
     */
    public class Demo1 {    
        public void test01(Map<String,User> map,List<User> list){
            System.out.println("Demo04.test01()");
        }    
        public Map<Integer,User> test02(){
            System.out.println("Demo04.test02()");
            return null;
        }    
        public static void main(String[] args) {
            try {            
                //获得指定方法参数泛型信息
                Method m = Demo1.class.getMethod("test01", Map.class,List.class);
                //调用时参数方法
                Type[] t = m.getGenericParameterTypes();
                for (Type paramType : t) {
                    System.out.println("#"+paramType);
                    if(paramType instanceof ParameterizedType){
                        Type[] genericTypes = ((ParameterizedType) paramType).getActualTypeArguments();
                        for (Type genericType : genericTypes) {
                            System.out.println("泛型类型:"+genericType);
                        }
                    }
                }            
                //获得指定方法返回值泛型信息
                Method m2 = Demo1.class.getMethod("test02", null);
                //调用的是返回的类型方法
                Type returnType = m2.getGenericReturnType();
                if(returnType instanceof ParameterizedType){
                        Type[] genericTypes = ((ParameterizedType) returnType).getActualTypeArguments();
    
                        for (Type genericType : genericTypes) {
                            System.out.println("返回值,泛型类型:"+genericType);
                        }                    
                }        
                
            } catch (Exception e) {
                e.printStackTrace();
            }    
        }
    }
     class User {
    }
    
    #java.util.Map<java.lang.String, com.bjsxt.test.User>
    泛型类型:class java.lang.String
    泛型类型:class com.bjsxt.test.User
    #java.util.List<com.bjsxt.test.User>
    泛型类型:class com.bjsxt.test.User
    返回值,泛型类型:class java.lang.Integer
    返回值,泛型类型:class com.bjsxt.test.User
    Demo5
  • 相关阅读:
    splay
    开车旅行(2012day1T3)
    LCT入门
    最小瓶颈路
    poj 3041 Asteroids
    sql waitfor 延时执行
    [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server 不存在或访问被拒绝
    SQL Server中行列转换
    sql中 with rollup 、with cube、grouping 统计函数用法
    sql 分组后 组内排名
  • 原文地址:https://www.cnblogs.com/ou-pc/p/7170099.html
Copyright © 2020-2023  润新知