Java - 枚举的 getDeclaringClass() 方法



描述

Java Enum getDeclaringClass() 方法返回与该枚举常量的枚举类型对应的 Class 对象。当且仅当 e1.getDeclaringClass() == e2.getDeclaringClass() 时,两个枚举常量 e1 和 e2 属于相同的枚举类型。

声明

以下是 java.lang.Enum.getDeclaringClass() 方法的声明

public final Class<E> getDeclaringClass()

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

参数

返回值

此方法返回与该枚举常量的枚举类型对应的 Class 对象。

异常

获取枚举的声明类示例

以下示例演示了使用其引用来获取枚举的 getDeclaringClass() 方法的使用。

Open Compiler
package com.tutorialspoint; // enum showing topics covered under Tutorials enum Tutorials { Java, HTML, Python; } public class EnumDemo { public static void main(String args[]) { Tutorials t1, t2, t3; t1 = Tutorials.Java; t2 = Tutorials.HTML; t3 = Tutorials.Python; // returns the Class object corresponding to an enum System.out.println(t2.getDeclaringClass()); } }

让我们编译并运行上面的程序,这将产生以下结果:

class com.tutorialspoint.Tutorials

获取枚举的声明类示例

以下示例演示了使用其类型直接获取枚举的 getDeclaringClass() 方法的使用。

Open Compiler
package com.tutorialspoint; // enum showing topics covered under Tutorials enum Tutorials { Java, HTML, Python; } public class EnumDemo { public static void main(String args[]) { Tutorials t1, t2, t3; t1 = Tutorials.Java; t2 = Tutorials.HTML; t3 = Tutorials.Python; // returns the Class object corresponding to an enum System.out.println(Tutorials.HTML.getDeclaringClass()); } }

让我们编译并运行上面的程序,这将产生以下结果:

class com.tutorialspoint.Tutorials

获取枚举的声明类时遇到异常的示例

以下示例演示了使用 getDeclaringClass() 方法检查枚举是否属于同一类型。由于我们比较的是两种不同类型的枚举,程序将给出编译器错误。

Open Compiler
package com.tutorialspoint; // enum showing topics covered under Tutorials enum Tutorials { Java, HTML, Python; } // a different enum with same values enum Tutorial { Java, HTML, Python; } public class EnumDemo { public static void main(String args[]) { if(Tutorials.HTML.getDeclaringClass() == Tutorials.Python.getDeclaringClass()) { System.out.println("Enums are of same type"); } if(Tutorial.HTML.getDeclaringClass() == Tutorials.Python.getDeclaringClass()) { System.out.println("Enums are of same type"); } } }

让我们编译并运行上面的程序,这将产生以下结果:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Incompatible operand types Class<Tutorial> and Class<Tutorials>

	at com.tutorialspoint.EnumDemo.main(EnumDemo.java:20)
java_lang_enum.htm
广告