如何使用反射(Java)调用私有静态方法? [英] How do I invoke a private static method using reflection (Java)?

查看:647
本文介绍了如何使用反射(Java)调用私有静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用私有静态方法。我有它的名字。我听说可以使用Java反射机制完成。我该怎么办?

I would like to invoke a private static method. I have its name. I've heard it can be done using Java reflection mechanism. How can I do it?

编辑:我在尝试调用方法时遇到的一个问题是如何指定其参数的类型。我的方法接收一个参数,其类型是Map。因此我无法做 Map< User,String> .TYPE (在运行时由于Java类型擦除而没有Map这样的东西)。有另一种获取方法的方法吗?

One problem I encountered when trying to invoke the method is how to specify the type of its argument. My method receives one argument and its type is Map. Therefore I cannot do Map<User, String>.TYPE (In run time there's no such a thing as Map because of Java Type erasure). Is there another way to get the method?

推荐答案

假设您要调用MyClass.myMethod(int x);

Let's say you want to call MyClass.myMethod(int x);

Method m = MyClass.class.getDeclaredMethod("myMethod", Integer.TYPE);
m.setAccessible(true); //if security settings allow this
Object o = m.invoke(null, 23); //use null if the method is static

这篇关于如何使用反射(Java)调用私有静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆