자바 반사 로 내부 클래스 정적 구성원 변 수 를 가 져 오 는 값 작업

어젯밤 한 동료 가 자바 반사 로 내부 정적 구성원 변수의 값 을 어떻게 해석 하 느 냐 고 물 어서 손 쉽게 썼 다.
쓸데없는 말 은 그만 하고 코드 를 바로 달 아 라!
해석 대상 클래스 구 조 는 다음 과 같 습 니 다.

/**
 * @Author changle
 * @Time 17/6/13.
 * @Desc to do
 */
public class Goods {
 static class apple{
  public static String version = "iphone6s[         ]";
  public static String date = "     2017-06-13";
 }
}
내부 클래스 정적 구성원 변수 도구 클래스 가 져 오기:

/**
 * @Author changle
 * @Time 17/6/13.
 * @Desc            
 */
public class TestParseInnerProValue {
 public static void main(String[] args) {
  Class<?> clasz = Goods.class;
  printInnerParamValue(clasz);
 }
 
 public static void printInnerParamValue(Class<?> clasz){
  Class innerClazz[] = clasz.getDeclaredClasses();
  for(Class claszInner : innerClazz){
   Field[] fields = claszInner.getDeclaredFields();
   for(Field field : fields){
    try {
     Object object = field.get(claszInner);
     System.out.println("    feild, name=" + field.getName()+", value="+ object.toString());
     //    
     /*
     *     feild, name=version, value=iphone6s[         ]
          feild, name=date, value=     2017-06-13
     * */
    } catch (IllegalAccessException e) {
     e.printStackTrace();
    }
 
   }
  }
 }
}
보충 지식:자바 는 반사 체 제 를 이용 하여 내부 류 의 개인 속성 과 방법 을 얻 고 개인 속성의 값 을 수정 합 니 다.
잔말 말고 코드 를 직접 붙 여 라.코드 에 주석 이 있다.다음 과 같다.

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
  @SuppressWarnings("unused")
  class Test1{
    //    
    private String color = "blue";
    
    //              
    private void queryColor(){
      System.out.println(color);
    }
    
    //         
    private void privateTest1(String param1) {
      System.out.println(">>>>>>" + param1 + ">>>>>>>>>" + color +">>>>>>>>>>");
    }
    
    //         
    private void privateTest2(String param1,String param2) {
      System.out.println(">>>>>>" + param1 + ">>>>>>>>>"+ param2 + ">>>>>>>>");
    }    
  }
  
  /** 
   * @Title: main 
   * @Description:                    ,          
   * @param args
   * @author songye 
   * @date Jul 19, 2018 10:17:32 AM
   * @return: void
   */
  public static void main(String[] args) {
    try {
      Test test = new Test(); 
      Test1 test1 = test.new Test1();
      //          
      Field colorField = Test1.class.getDeclaredField("color");
      //   true      private       
      colorField.setAccessible(true);
      System.out.println(colorField);
      //color    red
      colorField.set(test1, "red");
      
      //          ,    
      Method method = Test1.class.getDeclaredMethod("queryColor");
      //   true      private       
      method.setAccessible(true);
      System.out.println(method);
      //           ,    
      method.invoke(test1);
      
      //          ,     
      Method method1 = Test1.class.getDeclaredMethod("privateTest1",String.class);
      //   true      private       
      method1.setAccessible(true);
      System.out.println(method1);
      //           ,  test1   ,        
      method1.invoke(test1,"          !!!");
      
      //          ,     
      Method method2 = Test1.class.getDeclaredMethod("privateTest2",String.class,String.class);
      //   true      private       
      method2.setAccessible(true);
      System.out.println(method2);
      //           ,  test1   ,        
      method2.invoke(test1, "     1","     2");
    } catch (NoSuchFieldException e) {
      e.printStackTrace();
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }
}
실행 후 인쇄,아래:

이상 의 자바 는 반 사 를 이용 하여 내부 정적 구성원 변 수 를 가 져 오 는 값 조작 은 바로 작은 편집 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.여러분 께 참고 가 되 고 저 희 를 많이 사랑 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기