Java反射创建对象和调用方法

JavaBean:

View Code
 1 package com.mnid.beans;
2
3 public class Employee {
4 private String name;
5
6 public Employee() {
7
8 }
9
10 public String getName() {
11 return name;
12 }
13
14 public void setName(String name) {
15 this.name = name;
16 }
17
18 }

 反射代码:

View Code
 1 package com.mnid.reflect;
2
3 import java.lang.reflect.Constructor;
4 import java.lang.reflect.InvocationTargetException;
5 import java.lang.reflect.Method;
6
7 import com.mnid.beans.Employee;
8
9 public class ReflectTest {
10 public static void main(String[] args) throws Exception {
11 String name = "";
12 Employee employee = (Employee) Class.forName("com.mnid.beans.Employee")
13 .newInstance();
14 // Constructor constructor = Employee.class.getConstructor(null);
15 // Employee employee = (Employee) constructor.newInstance(null);
16 Class<? extends Employee> clazz = employee.getClass();
17 Method methodSet = clazz.getDeclaredMethod("setName", String.class);
18 Method methodGet = clazz.getDeclaredMethod("getName");
19 methodSet.invoke(employee, "Yang");
20 name = (String) methodGet.invoke(employee);
21 System.out.println(name);
22 }
23 }

 

posted on 2012-03-07 11:57  Mnid  阅读(2417)  评论(0编辑  收藏  举报