反射机制

来源:互联网 发布:mac视网膜壁纸 编辑:程序博客网 时间:2024/05/19 02:29

package com.phone.week6.day5.ref;

public class Student extends Object{

public String toString() {    return "Student [name=" + name + ", age=" + age + "]";}private String name;private int age;public String getName() {    return name;}public void setName(String name) {    this.name = name;}public int getAge() {    return age;}private void setAge(int age) {    this.age = age;}public Student() {    super();    // TODO Auto-generated constructor stub}public Student(String name, int age) {    super();    this.name = name;    this.age = age;}public Student(int age) {    super();    this.age = age;}private void test(String add,int code,double money){    System.out.println(add+"\t"+code+"\t"+money);}

}

package com.phone.week6.day5.ref;

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

public class Test {

public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {    Student s = new Student();    //获取Class对象的方法,一共有三种:    //第一种:通过对象的.getClass();    Student s = new Student();    Class cls = s.getClass();    第二种:通过类名.class属性    Class cls = Student.class;    第三种:通过Class类的forName(包名+类名的全路径)    //com.phone.week6.day5.ref.Student    Class cls = Class.forName("com.phone.week6.day5.ref.Student");    //只要获得内容时有getDeclared开头就是获得所有修饰符修饰的内容    //如果在get系列的方法上没有加Declared表示只能获得public修饰的内容    testCreateObject();    /*Constructor[] cs=cls.getDeclaredConstructors();    Field [] fs = cls.getDeclaredFields();    Method[] ms = cls.getDeclaredMethods();*/    /*Constructor[] cs = cls.getConstructors();    Field[] fs = cls.getFields();    Method[] ms = cls.getMethods();    System.out.println(cs.length+"\t"+fs.length+"\t"+ms.length);    //获得name属性    Field field=cls.getField("name");    System.out.println(field);*/}//通过class对象创建指定对象的两种方式private static void testCreateObject() throws ClassNotFoundException,        InstantiationException, IllegalAccessException,        NoSuchMethodException, InvocationTargetException {    Class cls = Class.forName("com.phone.week6.day5.ref.Student");    //这是第一种,这种实际上调用的就是你的类里的无参空构造,所以我们在创建一个类时,    //无论你这个类有多少个带参数的构造方法,你都应该把那个无参空构造写上,这是为了给反射用来创建对象的    Student stu=(Student)cls.newInstance();     //System.out.println(stu.name);    //这是第二种,通过构造方法来创建对象,如果有参数,要指定参数类型的class类型    Constructor con = cls.getConstructor(int.class);            stu = (Student)con.newInstance(30); //真正在创建对象时,传实参    //System.out.println(stu.age);}

}

package com.phone.week6.day5.ref;

import java.lang.reflect.Field;

import org.json.JSONException;
import org.json.JSONObject;

public class TestJSon {
/*利用反射机制将json字符串转化为对象
* 遍历Class中的所有属性,再到json字符串中找匹配的key,获取对应的值,并设置到通过反射创建的对象中的属性中去.*/
public static void main(String[] args) throws JSONException, InstantiationException, IllegalAccessException {
String s = “{name:lisi,age:33}”;
//1.把这个字符串转成JSON对象
JSONObject json = new JSONObject(s);
//2.先得到一个Class对象
Class cls = Student.class;
//3.根据cls对象来创建Student对象
Student stu = (Student) cls.newInstance();
//4.得到student对象的所有属性
Field[] fs= cls.getDeclaredFields();
for (Field f : fs) {
f.setAccessible(true); //取消权限检查
String name = f.getName() ;//得到属性名
Object value = json.get(name); //根据键得值
f.set(stu, value); //给属性设置值
}
System.out.println(stu);

}

}

package com.phone.week6.day5.ref;

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

public class TestStudetn {

public static void main(String[] args) {    try {        //1.创建CLASS对象,com.phone.week6.day5.ref.Student        Class cls=Class.forName("com.phone.week6.day5.ref.Student");        //2.创建实际要操作类的对象        Constructor cons = cls.getConstructor(null);        Student s =(Student)cons.newInstance(null);        //3.获得test方法的对象        Method m = cls.getDeclaredMethod("test", String.class,int.class,double.class);        //4.设置反射操作方法时取消权限检查        m.setAccessible(true);         //5.执行方法        m.invoke(s, "小小",518000,12345.67);    } catch (ClassNotFoundException e) {        e.printStackTrace();    } catch (NoSuchMethodException e) {        e.printStackTrace();    } catch (SecurityException e) {        e.printStackTrace();    } catch (InstantiationException e) {        e.printStackTrace();    } catch (IllegalAccessException e) {        e.printStackTrace();    } catch (IllegalArgumentException e) {        e.printStackTrace();    } catch (InvocationTargetException e) {        e.printStackTrace();    }}private static void test() {    try {        //1.获得指定类的Class对象        Class cls = Student.class;        //1.1根据cls来创建指定对象        Student s=(Student)cls.newInstance();        //2.获得指定属性        Field field =cls.getDeclaredField("name");        Field fage = cls.getDeclaredField("age");        //3. 给这个属性设置值,因为它是私有的,所以先取消权限检查        field.setAccessible(true);        fage.setAccessible(true);        //4.//给属性设置值        field.set(s, "虹桥");        fage.setInt(s, 20);        String name = (String) field.get(s);        int age = fage.getInt(s);        System.out.println(name+"\t"+age);        //调用指定方法    Method method=cls.getMethod("setName", String.class);    method.invoke(s, "浦东"); //执行方法,要传实际的参数    method=cls.getMethod("getName", null);    String names = (String) method.invoke(s, null);    System.out.println(names);    } catch (NoSuchFieldException e) {        e.printStackTrace();    } catch (SecurityException e) {        e.printStackTrace();    } catch (IllegalArgumentException e) {        e.printStackTrace();    } catch (IllegalAccessException e) {        e.printStackTrace();    } catch (InstantiationException e) {        e.printStackTrace();    } catch (NoSuchMethodException e) {        e.printStackTrace();    } catch (InvocationTargetException e) {        e.printStackTrace();    }}

}

0 0