正常模式:引入一个类的完整路径,然后通过new来实例化对象
反射模式:通过某个类的Class实例c来获取该类的信息(或创建该类实例对象)
利用反射操作对象属性
//Person实体类 public class Person { private int num=100; private String name="李兴华"; private String sex="女"; private int age=15; public Person(){ } public Person(int num){ this.num = num; } public Person(int num,String name){ this.num = num; this.name = name; } public Person(int num,String name,String sex,int age){ this.num = num; this.name = name; this.sex = sex; this.age = age; } public String toString(){ return "编号:"+num+" 姓名:"+name+" 性别:"+sex+" 年龄:"+age; } public void setNum(int num) { this.num = num; } public void setName(String name) { this.name = name; } public void setSex(String sex) { this.sex = sex; } public void setAge(int age) { this.age = age; } public int getNum() { return num; } public String getName() { return name; } public String getSex() { return sex; } public int getAge() { return age; } public void sayHello(){ System.out.println("hello"); } public String saySomethingoTo(Person person,String str){ return str+" "+person.name; } } //反射常见应用 public class ReflectApply { @Test //通过反射设置属性 public void setField() throws Exception{ Class<Person> c; c = Person.class; Person p = c.newInstance(); Field ageField = c.getDeclaredField("age"); //得到对象的age属性 ageField.setAccessible(true); //暴力反射,使属性可被访问 ageField.set(p,25); System.out.println(p); }通过反射来调用方法(接口等其他信息类似操作)
@Test //利用反射调用本类中的方法 public void useMethods() throws Exception{ Class<Person> c = Person.class; Person person = c.newInstance(); Method sayHello = c.getMethod("sayHello"); //获取sayHello方法对象 sayHello.invoke(person); //invoke方法中需要传入该类的实例对象 Method saySomethingoTo = c.getMethod("saySomethingoTo", Person.class, String.class); //获取saySomething方法对象 String rv = (String) saySomethingoTo.invoke(person, c.newInstance(), "你好啊"); //利用该对象调用inVoke函数实现方法调用 System.out.println(rv); }获取该类中的所有方法信息
@Test //通过反射获取所有方法 public void getMethods(){ Class<Person> c = Person.class; Method[] methods = c.getMethods(); //遍历法 // for (Method method : methods) { // System.out.println(method); // } //拼接法 for (int i = 0; i < methods.length; i++) { //得到方法修饰符 int md = methods[i].getModifiers(); //得到方法返回值类型 Class<?> ret = methods[i].getReturnType(); //得到方法的名称(不包含包类名) String name = methods[i].getName(); System.out.print("方法:"+Modifier.toString(md)+" "+ ret.getName()+" "+name+"("); //得到方法参数类型 Class<?>[] p = methods[i].getParameterTypes(); for (int j = 0; j < p.length; j++) { String name1 = p[j].getName(); System.out.print(name1+" arg"); if(j<p.length-1){ System.out.print(","); } } System.out.println("){}\n"); } }