熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java反射設置私有屬性和獲取屬性

2022-06-13   來源: 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;

  }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26324.html
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.