1CMSC 433 – Programming LanguageTechnologies and ParadigmsSpring 2005ReflectionApril 26, 20052Reflection• Remember project 1?– Used reflection to find module class• http://webserver:port/HelloWorld/Foo• We’ll cover some basics of reflection– Highly condensed version of• Reflection: Java Technology’s Secret Weapon, byOdendahl (on web page)3What is Reflection?• Makes classes, methods, and fields objectsthat can be manipulated at run time– Can determine fields and methods of class– Can instantiate class given a String containingits name– Can invoke methods given a String with name– Can create classes an runtime4What Reflection Isn’t• Doesn’t add any power to the language– Given access to all the source code• Not the solution to every problem– Use sparingly, if at all25java.lang.Class• Object of type Class represents a class– Useful for• Making instances of a class• Getting information about fields/methods– Most uses of reflection start with a Class• Primitive types also have a Class– e.g., int.class6Getting Some Class• Use Object method getClass()– Class c = “hello”.getClass();• Use class literal– Class c = String.class;• Use the class name– Class c = Class.forName(“java.lang.String”)7Making Objects• Class object for no-arg constructorClass c;Foo f = (Foo) c.newInstance();• Constructor object otherwiseClass c;Class[] cArg = { String.class };Constructor cons = c.getConstructor(cArg);Object[] consArg = { “hello” };Foo f = (Foo) cons.newInstance(consArg);8Working with Fields• Can get Field objects from Class– Can also get all fields in ClassClass c = x.getClass(); // get class of obj xField f = c.getField(“foo”);...(Type-of-foo) f.get(x); ......f.set(x, value);...39Invoking Methods• Get from Class object– Invoke just like constructorClass c = x.getClass();Class[] cArg = { String.class };Method m = c.getMethod(“bar”, cArg);Object[] mArg = { “hello” };Foo f = (m-result-type) m.invoke(x, mArg);10Putting It All Together• Example from JavaOne slides:public static void main(String [] args) throws Exception { Field f = System.class.getField(“out”); PrintStream out = (PrintStream) f.get(null); Class[] paramTypes = { String.class }; Method m = PrintStream.class.getMethod (“println”, paramTypes); String[] params = (String[]) Array.newInstance (String.class, 1); Array.set(params, 0, “Hello, world!”); m.invoke(out,
View Full Document