- import java.lang.reflect.*;
- class loadclass
- public class reflecttest {
- static
- {
- System.out.PRintln("Class reflecttest loaded");
- }
- public static void staicMethod()
- {
- System.out.println("staticMethod Called");
- }
- public void instanceMethod()
- {
- System.out.println("instanceMethod Called");
- }
- public static void main(String[] args) {
- Class c=reflecttest.class;
- try {
- Method method = c.getMethod("staicMethod", null);
- method.invoke(c,null);
- method.invoke(c.newInstance(),null);
- method=c.getMethod("instanceMethod",null);
- //method.invoke(c,null);
- //将抛出异常IllegalArgumentException:object is not an instance of declar
- ing class
- method.invoke(c.newInstance(),null);
- }
- catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }
复制代码 |