Java中的类 getDeclaredMethods() 方法和示例
Java.lang.Class 类的getDeclaredMethods()方法用于获取该类的方法,这些方法是private、public、protected或default及其成员或其成员类和接口的成员,但不是继承的方法。该方法以 Method 对象数组的形式返回该类的方法。
句法:
public Method[] getDeclaredMethods()
throws SecurityException
参数:此方法不接受任何参数。
返回值:该方法以Method对象数组的形式返回该类的方法。
异常如果存在安全管理器并且不满足安全条件,则此方法将引发SecurityException 。
下面的程序演示了 getDeclaredMethods() 方法。
示例 1:
Java
// Java program to demonstrate getDeclaredMethods() method
import java.util.*;
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Test");
System.out.println("Class represented by myClass: "
+ myClass.toString());
// Get the methods of myClass
// using getDeclaredMethods() method
System.out.println(
"DeclaredMethods of myClass: "
+ Arrays.toString(
myClass.getDeclaredMethods()));
}
}
Java
// Java program to demonstrate getDeclaredMethods() method
import java.util.*;
class Main {
public Object obj;
private void function() {}
Main()
{
class Arr {
};
obj = new Arr();
}
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Main");
System.out.println("Class represented by myClass: "
+ myClass.toString());
// Get the methods of myClass
// using getDeclaredMethods() method
System.out.println(
"DeclaredMethods of myClass: "
+ Arrays.toString(
myClass.getDeclaredMethods()));
}
}
myClass 代表的类:class Test
myClass 的声明方法:[public static void Test.main(Java.lang.String[]) throws Java.lang.ClassNotFoundException]
示例 2:
Java
// Java program to demonstrate getDeclaredMethods() method
import java.util.*;
class Main {
public Object obj;
private void function() {}
Main()
{
class Arr {
};
obj = new Arr();
}
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Main");
System.out.println("Class represented by myClass: "
+ myClass.toString());
// Get the methods of myClass
// using getDeclaredMethods() method
System.out.println(
"DeclaredMethods of myClass: "
+ Arrays.toString(
myClass.getDeclaredMethods()));
}
}
myClass 所代表的类:class Main
myClass 的声明方法:[public static void Main.main(Java.lang.String[]) throws Java.lang.ClassNotFoundException, private void Main。函数()]
参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#getDeclaredMethods–