Java反射

来源:互联网 发布:怎样软件编写 编辑:程序博客网 时间:2024/06/05 15:12

        JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制;

         这次做的项目sql语句是由反射自动生成的,平时用到反射的时候比较少,所以现在再次熟悉一下。

        反射的类:

public class ReflectEntity {public Integer id =11;public String name;public String sex;public double money;public void Hello(){System.out.println("Hello World!!!!");}}

        首先是关于是通过反射获取设置类的属性。

       

import java.lang.reflect.Field;public class Reflect {@SuppressWarnings("rawtypes")public static void main(String[] args) throws Exception {Class c=ReflectEntity.class;//c3是运行时类ReflectEntity r=new ReflectEntity();Class c3=r.getClass();//调用ReflectEntity无参构造方法Object o=c.newInstance();//获取所有的属性Field[] fs=c.getDeclaredFields();for(Field f:fs){System.out.println(f);//获取属性修饰符,列如public,static等,是int类型如:public:1,private:2,static4等System.out.println(f.getModifiers());//属性类型System.out.println(f.getType().getSimpleName());//属性的名字System.out.println(f.getName());}//获取特定属性Field id =c.getDeclaredField("id");//获取属性值System.out.println(id.get(o));//给o对象id赋值id.setAccessible(true);// 强制访问private变量id.set(o, 33);System.out.println(id.get(o));}}

通过反射调用方法

Class c=ReflectEntity.class;//获取所有方法Method[] s=c.getDeclaredMethods();for (Method m:s) {//通过invoke调用方法,需传入构造方法m.invoke(c.newInstance());}



原创粉丝点击