在 Java 中获取成员对象名称
getName() 方法用于获取由类对象表示的实体(例如接口、类、数组类、void 等)的名称。这些名称以字符串的形式返回。
下面给出了一个使用 getName() 方法获取成员对象名称的程序 −
示例
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Main {
public static void main(String[] argv) throws Exception {
Class c = java.lang.Integer.class;
Method m = c.getMethods()[0];
Field f = c.getFields()[0];
Constructor cons = c.getConstructors()[0];
String name;
name = c.getName();
System.out.println("Name of class: " + name);
name = m.getName();
System.out.println("Name of method: " + name);
name = f.getName();
System.out.println("Name of field: " + name);
name = cons.getName();
System.out.println("Name of constructor: " + name);
}
}输出
Name of class: java.lang.Integer Name of method: numberOfLeadingZeros Name of field: MIN_VALUE Name of constructor: java.lang.Integer
现在让我们了解一下上述程序。
getName() 方法用于获取类、方法、字段和构造函数的名称。然后显示这些名称。下面代码片段演示了这一点 −
Class c = java.lang.Integer.class;
Method m = c.getMethods()[0];
Field f = c.getFields()[0];
Constructor cons = c.getConstructors()[0];
String name;
name = c.getName();
System.out.println("Name of class: " + name);
name = m.getName();
System.out.println("Name of method: " + name);
name = f.getName();
System.out.println("Name of field: " + name);
name = cons.getName();
System.out.println("Name of constructor: " + name);
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP