加入收藏 | 设为首页 | 会员中心 | 我要投稿 江门站长网 (https://www.0750zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

Java访问类中private属性和技巧

发布时间:2021-11-24 19:45:02 所属栏目:教程 来源:互联网
导读:一般在其他类中是不能这个得到类中private属性和访问private方法的,但天无绝人之路,Java强大的反射机制可以完成这个任务。 建一个测试类A: package com.shao.test; public class A { private String testStr=just for test; private void get(int index,St

一般在其他类中是不能这个得到类中private属性和访问private方法的,但天无绝人之路,Java强大的反射机制可以完成这个任务。
建一个测试类A:
 
package com.shao.test;  
  
public class A {  
    private String testStr="just for test";  
    private void get(int index,String value){  
        System.out.println(index+":"+value+" and testStr:"+testStr);  
    }  
}  
现在我们来访问A中的testStr属性和get方法:
 
package com.shao.test;  
  
import java.lang.reflect.Field;  
import java.lang.reflect.InvocationTargetException;  
import java.lang.reflect.Method;  
  
public class B {  
      public static void main(String[]args) throws ClassNotFoundException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException{  
            Field field=Class.forName("com.shao.test.A").getDeclaredField("testStr");  
            field.setAccessible(true);  
            A a=new A();  
            System.out.println(field.getType().toString());   //print:class java.lang.String   
            System.out.println(field.getName());              //print:testStr   
            System.out.println(field.getModifiers());         //print:2   
            Object s=field.get(a);  
            System.out.println(s);                            //print:just for test   
            String x="Hello";  
            field.set(a, x);  
            System.out.println(field.get(a));                 //print:Hello   
            Method method=Class.forName("com.shao.test.A").getDeclaredMethod("get", new Class[]{int.class,String.class});  
            method.setAccessible(true);  
            method.invoke(a, 3,"apples");   //print:3:apples and testStr:Hello   
        }  
}  
属性使用Filed类获取,方法使用Method类去调用。

(编辑:江门站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读