Class loading and java reflection

Here is some simple example of class loading and java reflection.

package com.sun;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import com.sun1.TestClass;
public class MainClass {
@SuppressWarnings(“unchecked”)
public static void main(String[] args) {
System.out.println(“Testing classloading…”);
try{
Class clazz = Class.forName(“com.sun1.TestClass”);
Method [] methods = clazz.getDeclaredMethods();
TestClass tc = new TestClass();
for (Method method : methods) {
try{
method.invoke(tc, new Object[]{“Sunil Chauraha”});
}catch(InvocationTargetException e){
System.err.println(e.getMessage());
}catch (IllegalAccessException e) {
System.err.println(e.getMessage());
}
}
}catch(ClassNotFoundException cnf){
System.err.println(cnf.getMessage()+” : “+cnf);
}
}
}

package com.sun1;
public class TestClass {
public void pring(String value){
System.out.println(“The value passed is : “+value);
}
}

Advertisements
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

%d bloggers like this: