ReflectionJava looking at JavaWhat is reflection for?IDEsThe Class classGetting the class nameGetting all the superclassesGetting the class modifiers IGetting the class modifiers IIGetting interfacesExamining classes and interfacesGetting FieldsUsing Fields, IUsing Fields, IIConstructorsMethodsMethod methods, IMethod methods, IIArrays IArrays IIArrays IIIConcluding commentsThe EndJan 14, 2019Reflection2Java looking at JavaOne of the unusual capabilities of Java is that a program can examine itselfYou can determine the class of an object You can find out all about a class: its access modifiers, superclass, fields, constructors, and methodsYou can find out what is in an interfaceEven if you don’t know the names of things when you write the program, you can:Create an instance of a classGet and set instance variables Invoke a method on an objectCreate and manipulate arraysI guess this is called “reflection” because it’s as if a Java program could “look in a mirror” at itself3What is reflection for?In “normal” programs you don’t need reflectionYou do need reflection if you are working with programs that process programsTypical examples:A class browserA debuggerA GUI builderAn IDE, such as BlueJ or EclipseA program to grade student programs4IDEsMany IDEs are Java programs—what can they do?Compile a program (easy—just a system call)Load in your program after compilationFind out what classes you have, and what their constructors and methods areExecute your main methodCreate objects for you even without running your main methodSend messages to objects and display the resultsAll these capabilities, except compilation, are done with reflection5The Class classTo find out about a class, first get its Class objectIf you have an object obj, you can get its class object withClass c = obj.getClass();You can get the class object for the superclass of a Class c withClass sup = c.getSuperclass();If you know the name of a class (say, Button) at compile time, you can get its class object withClass c = Button.class;If you know the name of a class at run time (in a String variable str), you can get its class object withClass c = Class.forName(str);6Getting the class nameIf you have a class object c, you can get the name of the class with c.getName()getName returns the fully qualified name; that is, Class c = Button.class; String s = c.getName(); System.out.println(s);will print java.awt.ButtonClass Class and its methods are in java.lang, which is always imported and available7Getting all the superclassesgetSuperclass() returns a Class object (or null if you call it on Object, which has no superclass)The following code is from the Sun tutorial: static void printSuperclasses(Object o) { Class subclass = o.getClass(); Class superclass = subclass.getSuperclass(); while (superclass != null) { String className = superclass.getName(); System.out.println(className); subclass = superclass; superclass = subclass.getSuperclass(); }}8Getting the class modifiers IA Class object has an instance method getModifiers() that returns an intTo “decipher” the int result, we need methods of the Modifier class, which is in java.lang.reflect, so: import java.lang.reflect.*;Now we can do things like:if (Modifier.isPublic(m)) { System.out.println("public");}9Getting the class modifiers IIModifier contains these methods (among others):public static boolean isAbstract(int)public static boolean isFinal(int)public static boolean isInterface(int)public static boolean isPrivate(int)public static boolean isProtected(int)public static boolean isPublic(int)public static String toString(int)This will return a string such as"public final synchronized strictfp"10Getting interfacesA class can implement zero or more interfacesgetInterfaces() returns an array of Class objectsThese are the interfaces implemented by the classMore code from Sun:static void printInterfaceNames(Object o) { Class c = o.getClass(); Class[ ] theInterfaces = c.getInterfaces(); for (int i = 0; i < theInterfaces.length; i++) { String interfaceName = theInterfaces[i].getName(); System.out.println(interfaceName); }}Note that zero-length arrays are perfectly legal in Java11Examining classes and interfacesThe class Class represents both classes and interfacesTo determine if a given Class object c is an interface, use c.isInterface()To find out more about a class object, use:getModifiers()getFields() // "fields" == "instance variables"getConstructors()getMethods()isArray()12Getting Fieldspublic Field[] getFields() throws SecurityExceptionReturns an array of public Fields (variables)The length of the array may be zeroThe fields are not returned in any particular orderBoth locally defined and inherited instance variables are returned, but not static variablespublic Field getField(String7name) throws NoSuchFieldException, SecurityExceptionReturns the named public FieldIf no immediate field is found, the superclasses and interfaces are searched recursively13Using Fields, IIf f is a Field object, thenf.getName() returns the simple name of the fieldf.getType() returns the type (Class) of the fieldf.getModifiers() returns the Modifiers of the fieldf.toString() returns a String containing access modifiers, the type, and the fully qualified field nameExample: public java.lang.String Person.namef.getDeclaringClass() returns the Class in which this field is declared14Using Fields, IIThe values of the fields of an object obj may be accessed with:boolean f.getBoolean(obj), int f.getInt(obj), double f.getDouble(obj), etc., return the value of the field, assuming it is that type or can be widened to that typeObject f.get(obj) returns the value of the field, assuming it is an Objectvoid f.set(obj, value), void f.setBoolean(obj, bool), void f.setInt(obj, i), void f.getDouble(obj, d), etc. set the value of a field15ConstructorsIf c is a Constructor object, thenc.getName() returns the name of the constructor, as a String (this is the same as the name of the class)c.getDeclaringClass() returns the Class in which this constructor is declaredc.getModifiers() returns the Modifiers of the constructorc.getParameterTypes() returns an array of Class objects, in declaration
View Full Document