据我了解,构造函数、实例初始值设定项和静态初始值设定项只是具有特殊名称的方法。我知道<
和>
对于普通标识符来说是非法字符。
如何将这些特殊方法检索为 Method
对象(或等效的东西)并调用它们?您可以看一下我写的这段代码:
public class Program {
/**
* static <init>() {
* }
*/
static {
}
/**
* <init>() {
* }
*/
{
}
/**
* <cinit>() {
* }
*/
Program(){
}
public static void main(String[] args) throws ReflectiveOperationException {
//get native getDeclaredMethods method
Method Class$getDeclaredMethods0 = Class.class.getDeclaredMethod("getDeclaredMethods0", boolean.class);
Class$getDeclaredMethods0.setAccessible(true);
//list methods of this class
Method[] methods = (Method[])Class$getDeclaredMethods0.invoke(Program.class, false);
for (Method m : methods) {
System.out.println(m);
}
//Console output:
/*
public static void dirty.Program.main(java.lang.String[]) throws java.lang.ReflectiveOperationException
*/
}
}
最佳答案
你不能。您可以获取已声明构造函数的构造函数
实例,但没有表示可调用静态或实例初始值设定项的 Java 类型。
关于java - 如何将构造函数、实例初始值设定项、静态初始值设定项检索为方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28837161/