- package com;
-
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
-
-
-
- public class TestBean {
- private int age;
-
-
- public static void main(String []args) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchFieldException{
- try {
- Class<?> class1=Class.forName("com.TestBean");
- Object tObject=class1.newInstance();
- Field field=class1.getDeclaredField("age");
- field.setAccessible(true);
- field.set(tObject, 10);
- System.out.print(field.get(tObject));
-
- try {
- Method method=class1.getMethod("setAge", int.class);
- method.invoke(tObject, 11);
-
- Method getMethod=class1.getMethod("getAge");
- System.out.println(getMethod.invoke(tObject));
-
- } catch (NoSuchMethodException e) {
-
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
-
- e.printStackTrace();
- } catch (InvocationTargetException e) {
-
- e.printStackTrace();
- }
-
-
- } catch (ClassNotFoundException e) {
-
- e.printStackTrace();
- }
-
-
- }
-
-
- public int getAge() {
- return age;
- }
-
-
- public void setAge(int age) {
- this.age = age;
- }
- }
|