package com.study.reflect;
// 被调用方法
public class ReflectServiceImpl {
public void sayHello (String name) {
System.out.println("hello:"+name);
}
}
package com.study.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author zhang yong
* @describe 反射生成对象和反射调度方法
* @date 20180525
*/
public class ReflectInstance {
public Object reflect() {
ReflectServiceImpl reflectServiceImpl = null;
try {
// 反射生成对象
reflectServiceImpl = (ReflectServiceImpl) Class.forName("com.study.reflect.ReflectServiceImpl")
.newInstance();
// 反射调度方法
Method method = reflectServiceImpl.getClass().getMethod("sayHello", String.class);
method.invoke(reflectServiceImpl, "zhang san");
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return reflectServiceImpl;
}
public static void main(String[] args) {
new ReflectInstance().reflect();
}
}