簡體   English   中英

如何通過反射訪問私有方法和私有數據成員?

[英]How do I access private methods and private data members via reflection?

我知道我們可以通過反射來訪問私有構造函數@Sanjay T. Sharma在他的問題回答中提到: “instanceof Void”總是返回false嗎?

但是, @ duffymo

你可以使用反射訪問私有 - 方法,構造函數,數據成員,一切。

  1. 如何訪問私有方法和私有數據成員?
  2. 是否可以通過反射訪問局部變量?
  3. 有沒有辦法阻止任何人訪問私有構造函數,方法和數據成員?

1) 如何訪問私有方法和私有數據成員?

你可以在setAccessible(true)方法的幫助下完成它:

class Dummy{
    private void foo(){
        System.out.println("hello foo()");
    }
    private int i = 10;
}

class Test{
    public static void main(String[] args) throws Exception {
        Dummy d = new Dummy();

        /*---  [INVOKING PRIVATE METHOD]  ---*/
        Method m = Dummy.class.getDeclaredMethod("foo");
        //m.invoke(d); // Exception java.lang.IllegalAccessException
        m.setAccessible(true);//Abracadabra
        m.invoke(d); // Now it's OK

        /*---  [GETING VALUE FROM PRIVATE FIELD]  ---*/
        Field f = Dummy.class.getDeclaredField("i");
        //System.out.println(f.get(d)); // Not accessible now
        f.setAccessible(true); // Abracadabra
        System.out.println(f.get(d)); // Now it's OK

        /*---  [SETTING VALUE OF PRIVATE FIELD]  ---*/
        Field f2 = Dummy.class.getDeclaredField("i");
        //f2.set(d,20); // Not accessible now
        f2.setAccessible(true); // Abracadabra
        f2.set(d, 20); // Now it's OK
        System.out.println(f2.get(d));
    }
}

2) 是否可以通過反射訪問局部變量?

不能。局部變量不能在創建它們的塊之外訪問(有人可以說你可以將這樣的變量分配給像field = localVariable;這樣的字段field = localVariable;然后通過反射訪問這樣的字段,但這樣我們就會訪問 ,而不是變量 )。

3) 有沒有辦法阻止任何人訪問私有構造函數,方法和數據成員?

我認為對於constructorsmethods您可以使用stacktrace來檢查它是否被Reflection調用。
對於字段,我找不到阻止通過反射訪問它們的解決方案。

[警告:未經任何人批准。 我只是根據你的問題寫了它。]

class Dummy {
    private void safeMethod() {
        StackTraceElement[] st = new Exception().getStackTrace();
        // If a method was invoked by reflection, the stack trace would be similar
        // to something like this:
        /*
        java.lang.Exception
            at package1.b.Dummy.safeMethod(SomeClass.java:38)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        ->    at java.lang.reflect.Method.invoke(Method.java:601)
            at package1.b.Test.main(SomeClass.java:65)
        */
        //5th line marked by "->" is interesting one so I will try to use that info

        if (st.length > 5 &&
            st[4].getClassName().equals("java.lang.reflect.Method"))
            throw new RuntimeException("safeMethod() is accessible only by Dummy object");

        // Now normal code of method
        System.out.println("code of safe method");
    }

    // I will check if it is possible to normally use that method inside this class
    public void trySafeMethod(){
        safeMethod();
    }

    Dummy() {
        safeMethod();
    }
}

class Dummy1 extends Dummy {}

class Test {
    public static void main(String[] args) throws Exception {
        Dummy1 d1 = new Dummy1(); // safeMethod can be invoked inside a superclass constructor
        d1.trySafeMethod(); // safeMethod can be invoked inside other Dummy class methods
        System.out.println("-------------------");

        // Let's check if it is possible to invoke it via reflection
        Method m2 = Dummy.class.getDeclaredMethod("safeMethod");
        // m.invoke(d);//exception java.lang.IllegalAccessException
        m2.setAccessible(true);
        m2.invoke(d1);
    }
}

Test主要方法的輸出

code of safe method
code of safe method
-------------------
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at package1.b.Test.main(MyClass2.java:87)
Caused by: java.lang.RuntimeException: method safeMethod() is accessible only by Dummy object
    at package1.b.Dummy.safeMethod(MyClass2.java:54)
    ... 5 more
  1. 使用您鏈接到的答案中顯示的方法: setAccessible(true) ,它是Field,Constructor和Method的超類的方法。
  2. 沒有。
  3. 不,除非代碼在您控制的JVM中運行,否則您將在其中安裝安全管理器。 但是如果你給某人一個jar文件,並且他使用這個jar文件中的類,他將能夠訪問所有內容。

要訪問 私有字段,您需要調用Class.getDeclaredField(String name)enter code here方法。 檢查這個簡單的代碼:

public class PrivateObject {

  private String privateString = null;

  public PrivateObject(String privateString) {
    this.privateString = privateString;
  }
}

PrivateObject privateObject = new PrivateObject("The Private Value");

Field privateStringField = PrivateObject.class.
            getDeclaredField("privateString");

privateStringField.setAccessible(true);

String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue

要訪問私有方法,您需要調用Class.getDeclaredMethod(String name,Class [] parameterTypes)或Class.getDeclaredMethods()方法。

檢查這個簡單的代碼:

public class PrivateObject {

  private String privateString = null;

  public PrivateObject(String privateString) {
    this.privateString = privateString;
  }

  private String getPrivateString(){
    return this.privateString;
  }
}
PrivateObject privateObject = new PrivateObject("The Private Value");

Method privateStringMethod = PrivateObject.class.
        getDeclaredMethod("getPrivateString", null);

privateStringMethod.setAccessible(true);

String returnValue = (String)
        privateStringMethod.invoke(privateObject, null);

System.out.println("returnValue = " + returnValue);

請閱讀http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html上的詳細信息

 Area s=(Area)c.newInstance();  
 s.setRadius(10);
 System.out.println("Area: "+s.calculateArea(4));

 Method m[]=c.getDeclaredMethods(); 
  Constructor c1[]=c.getConstructors();  

 for(int i=0;i<m.length;i++)
     System.out.println(""+m[i]);

 for(int i=0;i<c1.length;i++)
     System.out.println(""+c1[i]);

示例如下:

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

class Test
{
    private int a = 5;   // Private data member

    private void call(int n) // Private method
    {
        System.out.println("in call()  n: " + n);
    }
}

public class Sample
{
    public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException
    {
        Class c = Class.forName("Test");

        Object obj = c.newInstance();

        //---- Accessing a private method
        Method m=c.getDeclaredMethod("call",new Class[]{int.class});
        m.setAccessible(true);
        m.invoke(obj,7);

       //---- Accessing a private data member
       Field d = c.getDeclaredField("a");
       d.setAccessible(true);
       System.out.println(d.getInt(obj));
    }
}

回答你的第三個問題:

  1. 有沒有辦法阻止任何人訪問私有構造函數,方法和數據成員?

回答:

是的,您可以限制訪問權限(當有人試圖訪問您的私有構造函數/方法/數據時,您可以拋出異常)

請參考以下示例:

******JavaSingleton Class******

package server;

public class JavaSingleton {

  private static final JavaSingleton INSTANCE = new JavaSingleton();

  private JavaSingleton() {
    if (INSTANCE != null) {
      throw new IllegalStateException("Inside JavaSingleton(): JavaSingleton " +
                                                        "instance already created.");
    }
    System.out.println("Inside JavaSingleton(): Singleton instance is being created.");
  }

  public static final JavaSingleton getInstance() {
    return INSTANCE;
  }
}


***Listing 2: JavaSingleton client***

import server.JavaSingleton;
import java.lang.reflect.*;

public class TestSingleton {

  public static void main(String[] args) throws ReflectiveOperationException {
    System.out.println("Inside main(): Getting the singleton instance using getInstance()...");
    JavaSingleton s = JavaSingleton.getInstance();

    System.out.println("Inside main(): Trying to use reflection to get another instance...");
    Class<JavaSingleton> clazz = JavaSingleton.class;
    Constructor<JavaSingleton> cons = clazz.getDeclaredConstructor();
    cons.setAccessible(true);
    JavaSingleton s2 = cons.newInstance();
  }
}

Output:

C:\singleton>java TestSingleton
Inside main(): Getting the singleton instance using getInstance()...
Inside JavaSingleton(): Singleton instance is being created.
Inside main(): Trying to use reflection to get another instance...
Exception in thread "main" java.lang.reflect.InvocationTargetException
  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
  at java.lang.reflect.Constructor.newInstance(Unknown Source)
  at TestSingleton.main(TestSingleton.java:13)
Caused by: java.lang.IllegalStateException: Inside JavaSingleton(): JavaSingleton instance already created.
  at server.JavaSingleton.<init>(JavaSingleton.java:7)
  ... 5 more

此示例適用於單例類(檢查構造函數),但您仍可以為要阻止從其他類訪問的私有方法實現此邏輯。

在這種情況下,您還將聲明一個靜態實例並在私有方法中檢查它的值,並在出現任何不需要的值時拋出錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM