Reflection Invoking Members (part 4)

By Using Reflection, we can invoke methods of objects even when we don’t have the proper references to them.

for example we have some objects in the heap from specific types that we don’t even have any knowledge about their types, but we need to invoke their methods. we could call their methods, if we know their specific references from their type, but just by calling

Object.method2(), which we know method2() is only defined in object MyObject, throwing exceptions, so how we can invoke method2 when we don’t have actual reference from MyObject class? the question is simple. it can be executed by below line of code:

this is our class:

public class ClassTesting {

private int number2present = 100;

public void writeSomething(int number2Present) {

System.out.println("ClassTesting.writeSomething() ... ");
System.out.println("input: " + number2Present + " + " + this.number2present + " = " + (number2Present + this.number2present));
this.number2present += number2Present;
System.out.println("call this method via Reflection API.");


and we can call method writeSomething(int num), by using below line of code:

try {

ClassTesting.class.getMethod("writeSomething", int.class).invoke(new ClassTesting(),200);

} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(ExpressClassInfo.class.getName()).log(Level.SEVERE, null, ex);

output will be something like:

ClassTesting.writeSomething() ... 
input: 200 + 100 = 300
call this method via Reflection API.
BUILD SUCCESSFUL (total time: 0 seconds)


we can get access to the Class object, then by calling getMethods and then finding the proper method and passing its proper typed parameters, we can easily invoke its methods.

Class<?> myclass = ClassTesting.class;

Method myMethod = myclass.getMethod("writeSomething", int.class);

myMethod.invoke(new ClassTesting(),200);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s