zoukankan      html  css  js  c++  java
  • java反射机制

    1. 什么是反射
    反射java语言中的一种机制,通过这种机制可以动态的实例化对象、读写属性、调用方法

    2一切反射相关的代码都从获得类(java.lang.Class)对象开始
    2.1 Class.forName(完整类名)

    	Class clzz=Class.forName("com.zking.refect.Student");
    		System.err.println(clzz);  

    结果

    class com.zking.refect.Student
    

      


    2.2 类名.class

    Class clzz=Student.class;
     System.err.println(clzz);

    结果

    class com.zking.refect.Student

    2.3 对象.getClass()

    Student s = new Student();
    Class clzz = s.getClass();
    System.out.println(clzz);

    结果

    class com.zking.refect.Student
    

      

    3. 反射三大作用(java.lang.reflect.*)
    3.1 实例化对象
    c.newInstance()

    Constructor.getConstructor/Constructor.getDeclaredConstructor
    注:一定要提供无参构造器

    Class<Student> clz=Student.class;
    	        //反射调用无参构造方法创建学生对象
    	        Student stu=(Student) clz.newInstance();
    	        System.out.println(stu);

    结果

    调用无参构造方法创建了一个学生对象
    

     

    3.2 动态调用方法
    Method m;
    m.invoke

    Student stu=new Student();
    	Class clz=stu.getClass();
    	Method m=clz.getDeclaredMethod("hello");
    	m.invoke(stu);

    结果

    你好!我是null

    3.3 读写属性
    Field set/get

    Student stu=new Student("s002","zs");
    Class clz=stu.getClass();
    	Field field=clz.getDeclaredField("age");
    	field.set(stu, 26);
    	System.out.println(stu);
    	
    

      结果

    Student [sid=s002, sname=zs, age=26]
    

      


    4. 访问修饰符

    获取修饰符之后返回的是int类型,并且是一个常量值,

    在java中修饰符有11种(6个常用的和5个不常用的)

    常用的修饰符为:public private protected friendly abstract final

    不常用的修饰符为: native strictfp synchronizend volatile transiend

    Student stu=new Student();
    Class clz=stu.getClass();
    //获取age的修饰符
    Field age=clz.getField("age");
    System.out.println(age.getModifiers());
    

     结果(1代表的修饰符为public)

    1
    

     

    	private String sid;
    
    	private String sname;
    
    	public Integer age;
    	
    

      

      

  • 相关阅读:
    Ubuntu 14.04上架IPSec+L2TP的方法
    Windows Server 2008 R2 FTP无法从外部访问的解决方法
    在Windows Server 2008 R2上打开ping的方法
    全站导航
    拉勾网招聘信息分析
    pandas之DataFrame
    pandas之Series
    matplolib学习
    numpy学习
    scrapy框架【爬虫的暂停和启动】
  • 原文地址:https://www.cnblogs.com/xmf3628/p/11024550.html
Copyright © 2011-2022 走看看