`

Simple of Java Reflection

    博客分类:
  • Java
阅读更多
define an entityObject:
java 代码
  1. class Employee {   
  2.     // 定义一个员工类   
  3.     public Employee() {   
  4.         age = 10;   
  5.         name = null;   
  6.     }   
  7.     // 将要被调用的方法   
  8.     public void setAge(int a) {   
  9.         age = a;   
  10.     }   
  11.     // 将要被调用的方法   
  12.     public int getAge() {   
  13.         return age;   
  14.     }   
  15.     // 将要被调用的方法   
  16.         public void printInfo(String name,int age){   
  17.         System.out.println("myName is:"+name+"  myAge is:"+age);   
  18.     }   
  19.     private int age;   
  20.     private String name;   
  21. }  

Test  Codes:

java 代码
  1. class ReflectTest{   
  2.     public static void main(String[] args){   
  3.         Employee emp=new Employee();   
  4.         Class c=emp.getClass();   
  5.         try{   
  6.             Method printInfo=c.getMethod("printInfo"new Class[]{String.class,int.class});   
  7.             Object[] args1=new Object[]{"zhuhaihua",23};   
  8.             printInfo.invoke(emp, args1);   
  9.         }catch(Exception e){   
  10.         }   
  11.     }   
  12. }  

just copy two pieces of code into the IDE(just like Eclipse) then run the ReflectTest class,you will get the result:
    myName is:zhuhaihua  myAge is:23

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics