JAVA反射举例

699 阅读3分钟

什么是反射

Java反射机制是在运行状态中,对于任意一个类,都能知道这个类的所以属性和方法;对于任何一个对象,都能够调用它的任何一个方法和属性;这样动态获取新的以及动态调用对象方法的功能就叫做反射。
简单来说反射就是解剖一个类,然后获取这个类中的属性和方法,前提是要获取这个类的Class对象
在java中给我们提供了几个这几个类用于描述编译后的各种对象

如何使用反射

A . 使用Class类,获取出被解剖的这个类的class文件对象 
B . 使用Class类方法,获取出类中的所有成员 
C . 将成员获取出来后,交给对应类,对应类中的方法,运行成员

如何获取,class文件对象

1、使用类的对象获取

每个类都使用Object作为父类,Object类方法 getClass() 
返回这个类的class文件对象,方法返回值Class类型对象

2、使用类的静态属性获取

类名.class 返回这个类的class文件对象.属性运行结果也是Class类型对象

3、使用Class类的静态方法获取

Class类静态方法 forName(String 类名) 传递字符串类名 
获取到这个类的class文件对象,方法返回值也是Class类型对象
不管用哪种方式获取的Class对象,他们都是相等的。

类:

java.lang.Class ---> 描述编译后的class文件的对象
java.lang.reflect.Constructor ---> 用于描述构造方法
java.lang.reflect.Field ---> 描述字段(成员变量)
java.lang.reflect.Method ---> 描述成员方法

定义demo

package com.test.demo; /**

  • 定义person类 */ public class Person {

}

package com.test.demo;

public class ReflectTest { public static void main(String[] args) throws ClassNotFoundException {

    //第1种方式获取Class对象

    Person p1=new Person();
    Class cc=p1.getClass();
    System.out.println(cc);

    //第2种方式获取Class对象
    Class cc2=Person.class;
    System.out.println(cc2);
    //第3种方式获取Class对象
    Class cc3=Class.forName("com.test.demo.Person");//全类名
    System.out.println(cc3);

    System.out.println(cc==cc2);
    System.out.println(cc2==cc3);
}

}

//输出结果 class com.test.demo.Person class com.test.demo.Person class com.test.demo.Person true true

获取构造

为Person类增加构造

public Person(){ System.out.println("Person类无参数构造"); } public Person(int a,int b,String s){ System.out.println("Person类有参数构造:a:"+a+" b:"+b+" s:"+s); }

private Person(int a){
    System.out.println("Person类有参数   私有 构造:a:"+a);
}

package com.test.demo;

import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException;

public class ReflectTest { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    Class clazz=Person.class;
    //获取Person类所有 公共 构造
    Constructor [] conarr=clazz.getConstructors();

    for(Constructor con :conarr){
        System.out.println(con);
    }
    //获取指定构造方法
    //无参数
    Constructor cc=clazz.getConstructor();
    Object oo=cc.newInstance();

    //有参数
    Constructor cc2=clazz.getConstructor(int.class,int.class,String.class);
    Object oo2=cc2.newInstance(1,2,"haha");

    //获取私有构造方法
    Constructor cc3=clazz.getDeclaredConstructor(int.class);
    //暴力访问
    cc3.setAccessible(true);
    Object oo3=cc3.newInstance(1);

    clazz.newInstance();//直接获取空参数构造,必须是public
}

}

输出结果

public com.test.demo.Person()

public com.test.demo.Person(int,int,java.lang.String)

Person类无参数构造

Person类有参数构造:a:1 b:2 s:haha

Person类有参数 私有 构造:a:1

Person类无参数构造

获取成员变量

为Person类增加成员变量

public String name="smt";
private String idcard="1001u09t";

@Override
public String toString() {
    // TODO Auto-generated method stub
    return "name:"+name+"  idcard:"+idcard;
}

package com.test.demo;

import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException;

public class ReflectTest { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {

    Class clazz = Person.class;
    Object obj = clazz.newInstance();
    // 获取Person类所有 公共 成员变量
    Field[] fields = clazz.getFields();
    for(Field s:fields){
        System.out.println(s);
    }

    Field field=clazz.getField("name");

    field.set(obj, "haha");

    System.out.println(obj);

    Field field2=clazz.getDeclaredField("idcard");
    field2.setAccessible(true);
    field2.set(obj, "123456");
    System.out.println(obj);
}

}

输出结果

Person类无参数构造

public java.lang.String com.test.demo.Person.name

name:haha idcard:1001u09t

name:haha idcard:123456

获取成员方法

为Person类增加成员方法

public void show(){
    System.out.println("show 空参数");
}
public void show(int a){
    System.out.println("show   a:"+a);
}   
private void show(String s){
    System.out.println("show   s:"+s);
}

public class ReflectTest { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {

    Class clazz = Person.class;
    Object obj = clazz.newInstance();
    // 获取Person类所有 公共 成员方法
    Method [] methods=clazz.getMethods();

    for(Method m:methods){
        System.out.println(m);
    }

    Method m=clazz.getMethod("show");
    m.invoke(obj);

    Method m1=clazz.getMethod("show",int.class);
    m1.invoke(obj,1);

    Method m2=clazz.getDeclaredMethod("show",String.class);
    m2.setAccessible(true);
    m2.invoke(obj,"smt");
}

}

输出结果:

Person类无参数构造

public java.lang.String com.test.demo.Person.toString()

public void com.test.demo.Person.show(int)

public void com.test.demo.Person.show()

public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException

public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException

public final void java.lang.Object.wait() throws java.lang.InterruptedException

public boolean java.lang.Object.equals(java.lang.Object)

public native int java.lang.Object.hashCode()

public final native java.lang.Class java.lang.Object.getClass()

public final native void java.lang.Object.notify()

public final native void java.lang.Object.notifyAll()

show 空参数

show a:1

show s:smt

反射在Android中的应用
设置菜单中图标的显示

@Override public boolean onMenuOpened(int featureId, Menu menu) { if (featureId == Window.FEATURE_ACTION_BAR && menu != null) { if (menu.getClass().getSimpleName().equals("MenuBuilder")) { try { Method m = menu.getClass().getDeclaredMethod( "setOptionalIconsVisible", Boolean.TYPE); m.setAccessible(true); m.invoke(menu, true); } catch (Exception e) { } } } return super.onMenuOpened(featureId, menu); }