gpt4 book ai didi

java - 有没有办法调用没有类对象的类的反射方法?

转载 作者:行者123 更新时间:2023-11-29 22:14:25 25 4
gpt4 key购买 nike

我正在尝试访问 SMSDispatcher 的 sendRawPdu 方法。我可以获取方法,但无法调用它,因为我必须有 SMSDispatcher 实例才能调用 mSendRawPdu.invoke(/* ??? */, pdus.encodedScAddress, pdus.encodedMessage, null,空);

从 SmsManager 调用方法效果很好,因为我可以获得像这样的对象 SmsManager sm = SmsManager.getDefault(); 并将其传递给 .invoke

try {

@SuppressWarnings("rawtypes")
Class c = Class.forName("com.android.internal.telephony.SMSDispatcher");
Method[] ms = c.getDeclaredMethods();

// List all methods
for (int i = 0; i < ms.length; i++) {
Log.d("ListMethos",ms[i].toString());
}

// Get method "sendRawPdu"
byte[] bb = new byte[1];
Method mSendRawPdu = c.getDeclaredMethod("sendRawPdu",bb.getClass(),bb.getClass(), PendingIntent.class, PendingIntent.class);
Log.d("success","success getting sendRawPdu");
mSendRawPdu.setAccessible(true);

// How to invoke the method not having object of type SMSDispatcher?
mSendRawPdu.invoke( /* ??? */ , pdus.encodedScAddress, pdus.encodedMessage, null, null );



} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

这个任务有可能的解决方案吗?

最佳答案

请参阅 Method#invoke(java.lang.Object, java.lang.Object...) 的文档

If the underlying method is an instance method, it is invoked using dynamic method lookup as documented in The Java Language Specification, Second Edition, section 15.12.4.4; in particular, overriding based on the runtime type of the target object will occur.

Throws:
NullPointerException - if the specified object is null and the method is an instance method.

所以,基本上,如果您传递 null 来调用实例方法,那么您会收到 NPE。这意味着没有对象就不可能调用实例方法。这是有道理的,因为您为什么要在没有实例的情况下调用实例方法。

例如

class MyClass {
public void myMethod() {
System.out.println("Hello Java Reflection!!!");
}
}

Method theMethod = MyClass.class.getDeclaredMethod("myMethod");
System.out.println(theMethod);
theMethod.setAccessible(true);
theMethod.invoke(null);

它抛出 NPE,但打印“Hello Java Reflection!!!”如果我将方法设为静态。

关于java - 有没有办法调用没有类对象的类的反射方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8810223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com