Java的反射非常強大,傳遞class, 可以動態的生成該類、取得這個類的所有信息,包括裏面的屬性、方法以及構造函數等,甚至可以取得其父類或父接口裏面的內容。
obj.getClass().getDeclaredMethods();//取得obj類中自己定義的方法, 包括私有的方法。
obj.getClass().getMethods();//取得obj類中自己定義的方法及繼承過來的方法, 但私有方法得不到。
同樣, 對field也是一樣,obj.getClass().getDeclaredFields();取得的是這個類中所有的屬性,包括私有的field; 對obj.getClass().getFields();//取得是自己以及接繼承來的屬性, 但不能取得自己的私有屬性。
- static Object create(Class clazz) throws Exception {
- Constructor con = clazz.getConstructor(String.class);
- Object obj = con.newInstance("test name");
- return obj;
- }
- static void invoke1(Object obj, String methodName)
- throws IllegalArgumentException, IllegalAccessException,
- InvocationTargetException, Exception, NoSuchMethodException {
- Method[] ms = obj.getClass().getDeclaredMethods();
- ms = obj.getClass().getMethods();
- for (Method m : ms) {
- // System.out.println(m.getName());
- if (methodName.equals(m.getName()))
- m.invoke(obj, null);
- }
- Method m = obj.getClass().getMethod(methodName, null);
- m.invoke(obj, null);
- }
- static void field(Class clazz) throws Exception {
- Field[] fs = clazz.getDeclaredFields();
- //fs = clazz.getFields();
- for (Field f : fs)
- System.out.println(f.getName());
- }
- static void annon(Class clazz) throws Exception {
- Annotation[] as = clazz.getAnnotations();
- }
- package com.yuqiaotech.simplejee.javase.reflect;
- import java.beans.BeanInfo;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- /**
- * 使用BeanInfo來設置和讀取對象的屬性。
- */
- public class BeanInfoSample {
- static class User{
- private String username;
- private String password;
- private String gender;
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getGender() {
- return gender;
- }
- public void setGender(String gender) {
- this.gender = gender;
- }
- }
- public static void main(String[] args) throws Exception {
- User u = new User();
- u.setUsername("Tom");
- u.setPassword("123");
- u.setGender("male");
- BeanInfo beanInfo = Introspector.getBeanInfo(User.class);
- PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
- for (PropertyDescriptor pd : propertyDescriptors) {
- String proName = pd.getName();
- Object v = pd.getReadMethod().invoke(u, null);
- System.out.println(proName+"="+v);
- }
- }
- }
- package com.yuqiaotech.simplejee.javase.reflect;
- import java.lang.reflect.*;
- /**
- * 1、獲取類的相關信息
- * 2、知道類名,實例化出對象
- * 3、動態調用實例的方法
- *
- *
- */
- public class ReflectSample {
- public static void main(String[] args) throws Exception {
- classInfo("com.yuqiaotech.simplejee.dao.BaseDao");
- newInstanceAndIncokeMethod();
- }
- private static void classInfo(String className) throws ClassNotFoundException{
- Class clazz = Class.forName(className);
- System.out.println("all implemented interfaces");
- Class[] allInterfaces = clazz.getInterfaces();
- for (int i = 0; i < allInterfaces.length; i++) {
- System.out.println(i+"."+allInterfaces[i]);
- }
- System.out.println("all super classes");
- Class superClass = clazz.getSuperclass();
- int i = 0;
- while(superClass != null){
- System.out.println(++i+"."+superClass);
- superClass = superClass.getSuperclass();
- }
- System.out.println("methods");
- Method[] methods = clazz.getMethods();
- for (int j = 0; j < methods.length; j++) {
- Method m = methods[j];
- System.out.println(j+"."+m.getName());
- }
- System.out.println("getConstructors");
- int k = 0;
- Constructor[] cs = String.class.getConstructors();
- for (Constructor c : cs) {
- System.out.println(++k+"."+c);
- }
- }
- private static void newInstanceAndIncokeMethod() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException{
- class Point{
- int x;
- int y;
- public Point(int x, int y){
- this.x = x;
- this.y = y;
- }
- public Point(){
- }
- public int getX() {
- return x;
- }
- public void setX(int x) {
- this.x = x;
- }
- public int getY() {
- return y;
- }
- public void setY(int y) {
- this.y = y;
- }
- public double getDistant(){
- return getDistant(0,0);
- }
- public double getDistant(int x, int y){
- int x1 = this.x-x;
- int y1 = this.y - y;
- return Math.sqrt(x1*x1 + y1*y1);
- }
- public String toString(){
- return "x="+x+",y="+y;
- }
- }
- System.out.println("常規方式:");
- Point ox = new Point(3,4);
- System.out.println(ox);
- System.out.println("1111result="+ox.getDistant());
- System.out.println("1111result="+ox.getDistant(5,8));
- System.out.println("反射方式:");
- //Class clazz = Point.class;
- Class clazz = Class.forName("com.yuqiaotech.simplejee.javase.reflect.ReflectSample$1Point");
- System.out.println("獲取Point類的構造函數對象,使用該對象得到一個Point類的實例");
- //獲取代表這個構造函數的對象public Point(int x, int y)
- Constructor c = clazz.getConstructor(int.class, int.class);
- Object[] args = new Object[] {3, 4};
- //Point o = new Point(3,4);
- Object o = c.newInstance(args);
- System.out.println(o);
- System.out.println("調用上述代碼得到的實例的public double getDistant()方法,並執行它");
- //public double getDistant()
- Method m = clazz.getMethod("getDistant", null);
- //Double result = o.getDistant();
- Double result = (Double)m.invoke(o, null);
- System.out.println("result="+result);
- System.out.println("調用上述代碼得到的實例的public double getDistant(int x, int y)方法," +
- "並執行getDistant(5,8)");
- //public double getDistant(int x, int y)
- Method m2 = clazz.getMethod("getDistant", new Class[]{int.class,int.class});
- //Double result2 = o.getDistant(5,8);
- Double result2 = (Double)m2.invoke(o, new Integer[]{5,8});
- System.out.println("result2="+result2);
- }
- }