Simple of Java Reflection

本文通过一个具体的Java代码示例介绍了如何使用Java反射机制来调用对象的方法。示例中定义了一个Employee类,并通过反射机制调用了其printInfo方法。
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值