define an entityObject:
java 代码
- class Employee {
- // 定义一个员工类
- public Employee() {
- age = 10;
- name = null;
- }
- // 将要被调用的方法
- public void setAge(int a) {
- age = a;
- }
- // 将要被调用的方法
- public int getAge() {
- return age;
- }
- // 将要被调用的方法
- public void printInfo(String name,int age){
- System.out.println("myName is:"+name+" myAge is:"+age);
- }
- private int age;
- private String name;
- }
Test Codes:
java 代码
- class ReflectTest{
- public static void main(String[] args){
- Employee emp=new Employee();
- Class c=emp.getClass();
- try{
- Method printInfo=c.getMethod("printInfo", new Class[]{String.class,int.class});
- Object[] args1=new Object[]{"zhuhaihua",23};
- printInfo.invoke(emp, args1);
- }catch(Exception e){
- }
- }
- }
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
本文通过一个具体的Java代码示例介绍了如何使用Java反射机制来调用对象的方法。示例中定义了一个Employee类,并通过反射机制调用了其printInfo方法。
2721

被折叠的 条评论
为什么被折叠?



