当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
Java反射设置私有属性和获取属性
发布时间:2010/8/6 10:43:30 来源:城市学习网 编辑:ziteng
  Java代码
  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) {
  // TODO Auto-generated catch block
  e.printStackTrace(); [NextPage]   } catch (IllegalArgumentException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  } catch (InvocationTargetException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  } catch (ClassNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  }
  public int getAge() {
  return age;
  }
  public void setAge(int age) {
  this.age = age;
  }
  }
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved