[英]Verifying the calling of a non-static method of a private static nested class of a static outer class
我如何驗證私有嵌套類的非靜態方法已被調用? 這是我到目前為止的內容:
new Verifications() {
{
Deencapsulation.invoke(MyClass.class.getDeclaredClasses()[0], "run" );
times = 4;
}
};
我得到這個:
java.lang.IllegalArgumentException: Attempted to invoke non-static method without an instance to invoke it on...
更新1:
@Dennis,盡管我正在獲得NPE
,但我已經嘗試了以下方法。 我想針對已在JVM中的單例驗證run
方法的運行情況,而不是為了調用方法m
而創建它的新實例(就像我在下面的代碼中所做的那樣)。 我嘗試調用m.invoke(null)
失敗。 有沒有辦法在外部嵌套類的運行實例上進行反射來驗證私有嵌套類中非靜態方法的調用中的調用(通過調用)?
new Verifications() {
Class c = MyClass.class.getDeclaredClasses()[0];
Method m = c.getDeclaredMethod("run");
//Method m = MyClass.class.getDeclaredClasses()[0].getDeclaredMethod("run", Integer.class, CallableClient.class);
//Deencapsulation.invoke(MyClass.class.getDeclaredClasses()[0], "run" );
Class[] a = new Class[] { Integer.class, CallableClient.class};
Object cc = Deencapsulation.newInstance(c, a);
//Object cc = Deencapsulation.newInstance(c, withInstanceOf(Integer.class), withInstanceOf(CallableClient.class));
{
try {
System.out.println(MyClass.class.getDeclaredClasses()[0].getName());
m.invoke(cc);
times = 3;
更新2:
嘗試獲得如下方法失敗后: final Field runnable = MyClass.class.getDeclaredField("nestedClassInstance"); runnable.setAccessible(true);
final Field runnable = MyClass.class.getDeclaredField("nestedClassInstance"); runnable.setAccessible(true);
然后使用getDeclaredMethods()
和getMethods()
,我認為這種方法存在太多錯誤,無法繼續進行下去。 我已更改測試中要測試的內容。 即使我介紹了內部嵌套類的實例,但我還是假設看不到run
方法的原因可能與以下一項或全部有關:包含類,構造函數和java的嵌套性質行為/決定,直到可以確保成功構造實例后才顯示實例方法。 好奇地知道為什么我不能確定。
既然您說過要查找是否要在運行時調用非靜態方法,那么這種反思應該會有所幫助。
假設m
是與您的方法相對應的Method
實例,則Modifier.isStatic(m.getModifiers())
將在且僅當方法為靜態時返回true,因此您可以在實際調用invoke
之前進行此檢查。 如果您還沒有Method
對象,那么將使用Class
的getMethod
Class
的東西。
編輯:上面所有這些都有助於在您通過invoke
方法之前檢查該方法是否靜態。 如果您想使用類似jmockit的方法來發現已調用了這樣的方法,那么我個人想知道這將如何幫助您獲得的IllegalArgumentException
,特別是如果通過invoke
其拋出, 因為試圖做異常消息說不允許的事情。 即使您可以模擬它,也可能涵蓋了更深層次的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.