關於外部訪問類的靜態屬性

今天遇到一個問題,別人問我如何在外部訪問類的私有屬性?測試

我很奇怪,我直接new這個對象不就能夠獲取了嗎? new Person().getName();這樣不就能夠獲取這個類的私有屬性值了嗎?code

不過對方說不是這種方式,後來我查了下,能夠經過反射的機制來獲取該屬性和方法:對象

類對象get

public class Examp {
	
	public int pub = 3;
	
	private int a = 4;
	
	private String s = "123";
	
	
	
	public void demo01(){
		System.out.println("======demo01===========");
	}
	
	private void demo02(){
		System.out.println("======demo02===========");
	}
	
	private void demo03(String s){
		a++;
		System.out.println("======demo03===s:"+s+"========a:"+a);
	}
	
}

測試類:it

public static void main(String args[]){ 
		Examp e=new Examp();  //初始化Exam實例  
	
		try {
            Field pub = e.getClass().getDeclaredField("pub");
            System.out.println("pub: "+pub.get(e));  
            Field  a = e.getClass().getDeclaredField("a");  
            Field s = e.getClass().getDeclaredField("s"); 
            a.setAccessible(true); 
            s.setAccessible(true);   
			
			System.out.println("s: "+s.get(e)); 
            s.set(e,"sss");  
            System.out.println("新的s: "+s.get(e)); 
			
            System.out.println("a: "+a.get(e));  
            a.set(e,8);  
            System.out.println("新的a: "+a.get(e));  
        } catch (NoSuchFieldException e1) {  
            e1.printStackTrace();  
        }catch (IllegalArgumentException e1) {  
            e1.printStackTrace();  
        } catch (IllegalAccessException e1) {  
            e1.printStackTrace();  
        }  
	
	
		try {  
              
            Method method1 = e.getClass().getDeclaredMethod("demo01");  
            method1.invoke(e);  
              
            Method method2 = e.getClass().getDeclaredMethod("demo02");  
            method2.setAccessible(true);  
            method2.invoke(e);  
              
            Method method3 = e.getClass().getDeclaredMethod("demo03",String.class);  
            method3.setAccessible(true);  
            method3.invoke(e,"ffff");  
        } catch (NoSuchMethodException e1) {  
            // TODO Auto-generated catch block  
            e1.printStackTrace();  
        } catch (SecurityException e1) {  
            // TODO Auto-generated catch block  
            e1.printStackTrace();  
        }catch (IllegalAccessException e1) {  
            // TODO Auto-generated catch block  
            e1.printStackTrace();  
        } catch (IllegalArgumentException e1) {  
            // TODO Auto-generated catch block  
            e1.printStackTrace();  
        } catch (InvocationTargetException e1) {  
            // TODO Auto-generated catch block  
            e1.printStackTrace();  
        }

	}

結果:io

pub: 3
s: 123
新的s: sss
a: 4
新的a: 8
======demo01===========
======demo02===========
======demo03===s:ffff========a:9

如上能夠獲取類的屬性,值和方法,不過這種方式就是說你必須知道這個類的屬性或方法的名字class

相關文章
相關標籤/搜索