OnJava8-Examples/enums/Reflection.java

67 lines
2.1 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// enums/Reflection.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Analyzing enums using reflection
2015-06-15 17:47:35 -07:00
import java.lang.reflect.*;
import java.util.*;
import onjava.*;
2015-06-15 17:47:35 -07:00
enum Explore { HERE, THERE }
public class Reflection {
public static Set<String> analyze(Class<?> enumClass) {
2015-12-02 09:20:27 -08:00
System.out.println(
"----- Analyzing " + enumClass + " -----");
2015-11-03 12:00:44 -08:00
System.out.println("Interfaces:");
2015-06-15 17:47:35 -07:00
for(Type t : enumClass.getGenericInterfaces())
2015-11-03 12:00:44 -08:00
System.out.println(t);
2015-12-02 09:20:27 -08:00
System.out.println(
"Base: " + enumClass.getSuperclass());
2015-11-03 12:00:44 -08:00
System.out.println("Methods: ");
2015-06-15 17:47:35 -07:00
Set<String> methods = new TreeSet<>();
for(Method m : enumClass.getMethods())
methods.add(m.getName());
2015-11-03 12:00:44 -08:00
System.out.println(methods);
2015-06-15 17:47:35 -07:00
return methods;
}
public static void main(String[] args) {
Set<String> exploreMethods = analyze(Explore.class);
Set<String> enumMethods = analyze(Enum.class);
2015-11-03 12:00:44 -08:00
System.out.println("Explore.containsAll(Enum)? " +
2015-06-15 17:47:35 -07:00
exploreMethods.containsAll(enumMethods));
2015-11-03 12:00:44 -08:00
System.out.print("Explore.removeAll(Enum): ");
2015-06-15 17:47:35 -07:00
exploreMethods.removeAll(enumMethods);
2015-11-03 12:00:44 -08:00
System.out.println(exploreMethods);
2015-06-15 17:47:35 -07:00
// Decompile the code for the enum:
2016-07-07 14:58:56 -06:00
OSExecute.command("javap -cp build/classes/main Explore");
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
----- Analyzing class Explore -----
Interfaces:
Base: class java.lang.Enum
Methods:
[compareTo, equals, getClass, getDeclaringClass, hashCode,
name, notify, notifyAll, ordinal, toString, valueOf,
values, wait]
----- Analyzing class java.lang.Enum -----
Interfaces:
java.lang.Comparable<E>
interface java.io.Serializable
Base: class java.lang.Object
Methods:
[compareTo, equals, getClass, getDeclaringClass, hashCode,
name, notify, notifyAll, ordinal, toString, valueOf, wait]
Explore.containsAll(Enum)? true
Explore.removeAll(Enum): [values]
Compiled from "Reflection.java"
final class Explore extends java.lang.Enum<Explore> {
public static final Explore HERE;
public static final Explore THERE;
public static Explore[] values();
public static Explore valueOf(java.lang.String);
static {};
}
2015-09-07 11:44:36 -06:00
*/