java

位置:IT落伍者 >> java >> 浏览文章

Java反射设置私有属性和获取属性


发布日期:2018年10月01日
 
Java反射设置私有属性和获取属性

Java代码

package com;

import javalangreflectField;

import javalangreflectInvocationTargetException;

import javalangreflectMethod;

public class TestBean {

private int age;

public static void main(String []args) throws InstantiationException IllegalAccessException SecurityException NoSuchFieldException{

try {

Class<?> class=ClassforName(comTestBean);

Object tObject=classnewInstance();

Field field=classgetDeclaredField(age);

fieldsetAccessible(true); //设置私有属性范围

fieldset(tObject );

Systemoutprint(fieldget(tObject));

try {

Method method=classgetMethod(setAge intclass);

methodinvoke(tObject );

Method getMethod=classgetMethod(getAge);

Systemoutprintln(getMethodinvoke(tObject));

} catch (NoSuchMethodException e) {

// TODO Autogenerated catch block

eprintStackTrace();

} catch (IllegalArgumentException e) {

// TODO Autogenerated catch block

eprintStackTrace();

} catch (InvocationTargetException e) {

// TODO Autogenerated catch block

eprintStackTrace();

}

} catch (ClassNotFoundException e) {

// TODO Autogenerated catch block

eprintStackTrace();

}

}

public int getAge() {

return age;

}

public void setAge(int age) {

thisage = age;

}

}

               

上一篇:Java类的热替换——概念、设计与实现

下一篇:Java2下Applet数字签名