如何通过类引用访问静态方法 [英] How to access a static method via a class reference
本文介绍了如何通过类引用访问静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A {
public static void foo() {}
}
class B {
public static void foo() {}
}
我有 Class clazz = A.class;或B.class
;
假设它可能被分配为"A"或"B",我如何通过"clazz"访问它
How do I access this via "clazz" assuming it might be assigned either 'A' or 'B'
推荐答案
只能使用反射来访问这些方法.您不能直接引用类,只能直接引用类类型的实例.
It is only possible to access those methods using reflection. You cannot reference a class directly, only an instance of type Class.
要使用反射来调用方法名(int a,字符串b):
To use reflection to invoke methodname(int a, String b):
Method m = clazz.getMethod("methodname", Integer.class, String.class);
m.invoke(null, 1, "Hello World!");
请参见 Method.invoke()
您可能需要重新考虑您的设计,以避免需要动态调用静态方法.
You may want to think about your design again, to avoid the need to dynamically call static methods.
这篇关于如何通过类引用访问静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文