-------android培训、java培训、期待与您交流! ----------
反射机制:所谓的反射机制就是java语言在运行时拥有一项自观的能力。通过这种能力可以彻底的了解自身的情况为下一步的动作做准备。下面具体介绍一下java的反射机制。这里你将颠覆原来对java的理解。
Java的反射机制的实现要借助于4个类:Class,Constructor,Field,Method;其中Class代表的时类对 象,Constructor-类的构造器对象,Field-类的属性对象,Method-类的方法对象。通过这四个对象我们可以粗略的看到一个类的各个组 成部分。
0.辅助类
0.0.China接口
package com.Lland.Reflection; public interface China { public static final String CHINANAME = "中国"; public void sayChina(); public void sayHello(String name, int age); }
0.1.Person类
package com.Lland.Reflection; public class Person implements China { private String name; private int age; public Person() { } public Person(String name) { this.name = name; } public Person(int age) { this.age = age; } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString() { return "[" + this.name + " " + this.age + "]"; } public void sayChina() { System.out.println(China.CHINANAME); } public void sayHello(String name, int age) { System.out.println("你好,我叫" + name + ",今年" + age + "岁。"); } }
1.通过对象获得该对象完整的类名、包名
package com.Lland.Reflection; public class GetClass { /** * @discription:通过对象获得该对象完整的类名、包名 */ public static void main(String[] args) { Person person = new Person(); System.out.println(person.getClass().getName()); } }
运行结果:com.Lland.Reflection.Person
2.实例化Class对象
package com.Lland.Reflection; public class InstantiateClass { /** * @discription:3种方式实例化Class类对象 */ public static void main(String[] args) { Class<?> class_1 = null; Class<?> class_2 = null; Class<?> class_3 = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); } catch (Exception e) { e.printStackTrace(); } class_2 = new Person().getClass(); class_3 = Person.class; System.out.println("类名称(class_1):" + class_1.getName()); System.out.println("类名称(class_2):" + class_2.getName()); System.out.println("类名称(class_3):" + class_3.getName()); } }
运行结果:类名称(class_1):com.Lland.Reflection.Person 类名称(class_2):com.Lland.Reflection.Person 类名称(class_3):com.Lland.Reflection.Person3.Class类实例化其他类的对象
3.1.无参
package com.Lland.Reflection; public class InstantiatePerson { /** * @discription:Class类实例化其他类的对象-无参 */ public static void main(String[] args) { Class<?> class_1 = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); } catch (Exception e) { e.printStackTrace(); } Person person = null; try { person = (Person) class_1.newInstance(); } catch (Exception e) { e.printStackTrace(); } person.setName("Lland"); person.setAge(18); System.out.println(person); } }
运行结果:[Lland 18]3.2.有参
package com.Lland.Reflection; import java.lang.reflect.Constructor; public class InstantiatePersonWithParameter { /** * @discription:Class类实例化其他类的对象-有参 */ public static void main(String[] args) { Class<?> class_1 = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); } catch (Exception e) { e.printStackTrace(); } Person person1 = null; Person person2 = null; Person person3 = null; Person person4 = null; // 取得全部的构造函数 Constructor<?> constructors[] = class_1.getConstructors(); try { person1 = (Person) constructors[0].newInstance("Lland"); person2 = (Person) constructors[1].newInstance(18); person3 = (Person) constructors[2].newInstance("Lland", 18); person4 = (Person) constructors[3].newInstance(); } catch (Exception e) { e.printStackTrace(); } System.out.println(person1); System.out.println(person2); System.out.println(person3); System.out.println(person4); } }
运行结果:[Lland 0] [null 18] [Lland 18] [null 0]4.获取其它类实现的接口
package com.Lland.Reflection; public class GetInterface { /** * @discription:获取其它类实现的接口 */ public static void main(String[] args) { Class<?> class_1 = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); } catch (Exception e) { e.printStackTrace(); } //获取所有的接口 Class<?> interfaces[] = class_1.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { System.out.println(class_1.getName() + "类实现的接口:" + interfaces[i].getName()); } } }
运行结果:com.Lland.Reflection.Person类实现的接口:com.Lland.Reflection.China5.获取其它类继承的父类
package com.Lland.Reflection; public class GetSuperClass { /** * @discription:获取其它类继承的父类 */ public static void main(String[] args) { Class<?> class_1 = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); } catch (Exception e) { e.printStackTrace(); } // 取得父类 Class<?> superClass = class_1.getSuperclass(); System.out.println(class_1.getName() + "类继承的父类为:" + superClass.getName()); } }
运行结果:com.Lland.Reflection.Person类继承的父类为:java.lang.Object6.获取其它类构造方法
package com.Lland.Reflection; import java.lang.reflect.Constructor; public class GetConstructor { /** * @discription:获取其它类构造方法 */ public static void main(String[] args) { Class<?> class_1 = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); } catch (Exception e) { e.printStackTrace(); } Constructor<?> constructors[] = class_1.getConstructors(); for (int i = 0; i < constructors.length; i++) { System.out.println("构造方法:" + constructors[i]); } } }
运行结果:构造方法:public com.Lland.Reflection.Person(java.lang.String) 构造方法:public com.Lland.Reflection.Person(int) 构造方法:public com.Lland.Reflection.Person(java.lang.String,int) 构造方法:public com.Lland.Reflection.Person()7.获取其他类构造方法权限
package com.Lland.Reflection; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; public class GetModifiers { /** * @discription:获取其他类构造方法权限 */ public static void main(String[] args) { Class<?> class_1 = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); } catch (Exception e) { e.printStackTrace(); } Constructor<?> constructors[] = class_1.getConstructors(); for (int i = 0; i < constructors.length; i++) { Class<?> parameters[] = constructors[i].getParameterTypes(); System.out.print("构造方法: "); int modifier = constructors[i].getModifiers(); System.out.print(Modifier.toString(modifier) + " "); System.out.print(constructors[i].getName()); System.out.print(" ("); for (int j = 0; j < parameters.length; j++) { System.out.print(parameters[j].getName() + " arg" + i); if (j < parameters.length - 1) { System.out.print(", "); } } System.out.println(") {}"); } } }
运行结果:构造方法: public com.Lland.Reflection.Person (java.lang.String arg0) {} 构造方法: public com.Lland.Reflection.Person (int arg1) {} 构造方法: public com.Lland.Reflection.Person (java.lang.String arg2, int arg2) {} 构造方法: public com.Lland.Reflection.Person () {}8.获取其他类的方法
package com.Lland.Reflection; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class GetMethod { /** * @discription:获取其他类的方法 */ public static void main(String[] args) { Class<?> class_1 = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); } catch (Exception e) { e.printStackTrace(); } Method methods[] = class_1.getMethods(); for (int i = 0; i < methods.length; i++) { Class<?> returnType = methods[i].getReturnType(); Class<?> parameters[] = methods[i].getParameterTypes(); int modifier = methods[i].getModifiers(); System.out.print(Modifier.toString(modifier) + " "); System.out.print(returnType.getName() + " "); System.out.print(methods[i].getName() + " "); System.out.print("("); for (int j = 0; j < parameters.length; j++) { System.out.print(parameters[j].getName() + " " + "arg" + j); if (j < parameters.length - 1) { System.out.print(", "); } } Class<?> exceptions[] = methods[i].getExceptionTypes(); if (exceptions.length > 0) { System.out.print(") {} throws "); for (int j = 0; j < exceptions.length; j++) { System.out.print(exceptions[j].getName() + " "); if (j < exceptions.length - 1) { System.out.print(", "); } } } else { System.out.print(") {}"); } System.out.println(); } } }
运行结果:public java.lang.String toString () {} public java.lang.String getName () {} public void setName (java.lang.String arg0) {} public int getAge () {} public void setAge (int arg0) {} public void sayChina () {} public void sayHello (java.lang.String arg0, int arg1) {} public final void wait (long arg0, int arg1) {} throws java.lang.InterruptedException public final native void wait (long arg0) {} throws java.lang.InterruptedException public final void wait () {} throws java.lang.InterruptedException public boolean equals (java.lang.Object arg0) {} public native int hashCode () {} public final native java.lang.Class getClass () {} public final native void notify () {} public final native void notifyAll () {}9.获取其他类的属性
package com.Lland.Reflection; import java.lang.reflect.Field; import java.lang.reflect.Modifier; public class GetField { /** * @discription:获取其他类的属性 */ public static void main(String[] args) { Class<?> class_1 = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); } catch (Exception e) { e.printStackTrace(); } System.out.println("本类属性:"); // 取得本类的全部属性 Field[] fields = class_1.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { // 权限修饰符 int modifier = fields[i].getModifiers(); String modifierString = Modifier.toString(modifier); // 属性类型 Class<?> type = fields[i].getType(); System.out.println(modifierString + " " + type.getName() + " " + fields[i].getName() + ";"); } System.out.println("实现接口或继承父类的属性:"); // 取得实现的接口或者父类的属性 Field[] filedsFromInterfaceOrSupClass = class_1.getFields(); for (int j = 0; j < filedsFromInterfaceOrSupClass.length; j++) { // 权限修饰符 int modifier = filedsFromInterfaceOrSupClass[j].getModifiers(); String modifierString = Modifier.toString(modifier); // 属性类型 Class<?> type = filedsFromInterfaceOrSupClass[j].getType(); System.out.println(modifierString + " " + type.getName() + " " + filedsFromInterfaceOrSupClass[j].getName() + ";"); } } }
运行结果:本类属性: private java.lang.String name; private int age; 实现接口或继承父类的属性: public static final java.lang.String CHINANAME;10.调用其他类的方法
package com.Lland.Reflection; import java.lang.reflect.Method; public class CallMethod { /** * @discription:调用其他类的方法 */ public static void main(String[] args) { Class<?> class_1 = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); } catch (Exception e) { e.printStackTrace(); } try { // 调用Person类中的sayChina方法 Method method = class_1.getMethod("sayChina"); method.invoke(class_1.newInstance()); // 调用Person的sayHello方法 method = class_1.getMethod("sayHello", String.class, int.class); method.invoke(class_1.newInstance(), "Lland", 20); } catch (Exception e) { e.printStackTrace(); } } }
运行结果:中国 你好,我叫Lland,今年18岁。11.调用其他类的setter和getter方法
package com.Lland.Reflection; import java.lang.reflect.Method; public class CallSetterAndGetter { /** * @discription:调用其他类的setter和getter方法 */ public static void main(String[] args) { Class<?> class_1 = null; Person person = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); } catch (Exception e) { e.printStackTrace(); } try { person = (Person) class_1.newInstance(); } catch (Exception e) { e.printStackTrace(); } try { Method method = person.getClass().getMethod("setName" , String.class); method.invoke(person, "Lland"); method = person.getClass().getMethod("setAge" , int.class); method.invoke(person, 18); } catch (Exception e) { e.printStackTrace(); } try { Method method = person.getClass().getMethod("getName"); System.out.println(method.invoke(person)); method = person.getClass().getMethod("getAge"); System.out.println(method.invoke(person)); } catch (Exception e) { e.printStackTrace(); } } }
运行结果:Lland 1812.操作其他类的属性
package com.Lland.Reflection; import java.lang.reflect.Field; public class OperateField { /** * @discription:操作其他类的属性 */ public static void main(String[] args) { Class<?> class_1 = null; Person person = null; try { class_1 = Class.forName("com.Lland.Reflection.Person"); person = (Person) class_1.newInstance(); Field field = class_1.getDeclaredField("name"); field.setAccessible(true); field.set(person, "Lland"); System.out.println(field.get(person)); field = class_1.getDeclaredField("age"); field.setAccessible(true); field.set(person, 18); System.out.println(field.get(person)); } catch (Exception e) { e.printStackTrace(); } } }
运行结果:Lland 18