簡體   English   中英

如何從java類外部調用私有方法

[英]How to call a private method from outside a java class

我有一個Dummy類,它有一個名為sayHello的私有方法。 我想從Dummy外面打電話給sayHello 我認為它應該可以反射,但我得到一個IllegalAccessException 有任何想法嗎???

在使用其invoke方法之前,在Method對象上使用setAccessible(true)

import java.lang.reflect.*;
class Dummy{
    private void foo(){
        System.out.println("hello foo()");
    }
}

class Test{
    public static void main(String[] args) throws Exception {
        Dummy d = new Dummy();
        Method m = Dummy.class.getDeclaredMethod("foo");
        //m.invoke(d);// throws java.lang.IllegalAccessException
        m.setAccessible(true);// Abracadabra 
        m.invoke(d);// now its OK
    }
}

首先,您必須獲得類,這是非常簡單的,然后使用getDeclaredMethod按名稱獲取方法,然后您需要將方法設置為可由Method對象上的setAccessible方法訪問。

    Class<?> clazz = Class.forName("test.Dummy");

    Method m = clazz.getDeclaredMethod("sayHello");

    m.setAccessible(true);

    m.invoke(new Dummy());
method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
method.invoke(object);

如果要將任何參數傳遞給私有函數,可以將其作為調用函數的第二個,第三個.....參數傳遞。 以下是示例代碼。

Method meth = obj.getClass().getDeclaredMethod("getMyName", String.class);
meth.setAccessible(true);
String name = (String) meth.invoke(obj, "Green Goblin");

完整的例子你可以看到這里

使用java反射訪問私有方法(帶參數)的示例如下:

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Test
{
    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");  //specify class name in quotes
        Object obj=c.newInstance();

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

暫無
暫無

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

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