UserInfo 类;
public class UserInfo {
public String name;
private String age;
protected String sex;
public UserInfo(){
}
public UserInfo(String name){
this.name=name;
}
public void say(String name){
System.out.println(name+"说:XX");
}
private int add(int i,int j){
return i+j;
}
protected String hello(){
return "Hello World!";
}
public String toString(){
return name;
}
}
--------------------------------------------------------------------------------------------------------
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class FlectTest {
/**
* @param args
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
* @throws NoSuchFieldException
*/
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
/*Class cla=
Class.forName("date2.reflect.UserInfo");//通过字符串找到类
//获取当前类及其父类中public修饰的方法
// Method[] methods=cla.getMethods();
//获取当前类中出现的方法,父类中的方法获取不到
Method[] methods=cla.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
Object obj=cla.newInstance();
Method method=cla.getDeclaredMethod("add",
int.class,int.class);
method.setAccessible(true);
Object s=method.invoke(obj, 12,34);
System.out.println(s);
System.out.println("=====================");
Field[] fields=cla.getDeclaredFields();
for (Field field : fields) {
//System.out.println(field.getName()+":"+field.getType().getName());
}
Field field=cla.getDeclaredField("age");
field.setAccessible(true);
//如果该对象为static在不用指明obj,为null
field.set(obj, "zhang san");
Object value=field.get(obj);
System.out.println(value);
System.out.println("--------------");
Constructor cons=
cla.getDeclaredConstructor(String.class);
Object o=cons.newInstance("accp");
System.out.println(o);
*/