Difference between revisions of "Java reflection"

From John Freier
Jump to: navigation, search
 
Line 7: Line 7:
 
  Constructor<AClazz> constructor = AClazz.class.getConstructor(a);
 
  Constructor<AClazz> constructor = AClazz.class.getConstructor(a);
 
  return (AClazz) constructor.newInstance("hello");
 
  return (AClazz) constructor.newInstance("hello");
 +
 +
 +
Invoke a method
 +
Class<?> c = Class.forName("class name");
 +
Method  method = c.getDeclaredMethod ("method name", parameterTypes)
 +
method.invoke (objectToInvokeOn, params)

Latest revision as of 09:24, 9 May 2012

Reflection

This is an example of reflection, Creating an instants

AClazz a = new AClass("hello");
Class<?> AClazz = a.getClass();
Constructor<AClazz> constructor = AClazz.class.getConstructor(a);
return (AClazz) constructor.newInstance("hello");


Invoke a method

Class<?> c = Class.forName("class name");
Method  method = c.getDeclaredMethod ("method name", parameterTypes)
method.invoke (objectToInvokeOn, params)