反射字段:
package heng.java.reflect.field;
import java.lang.reflect.Field;
public class ReflectFieldDemo {
public static void main(String[] args) {
/*
* 获取类中的成员。反射字段。
*/
try {
getFieldDemo();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void getFieldDemo() throws ClassNotFoundException, Exception, Exception{
String className = "heng.java.reflect.constructor.Person";
Class clazz = Class.forName(className);
//
//Field field = clazz.getField("age");//该方法只获取公有的。
Field field = clazz.getDeclaredField("age");
//要对非静态的字段操作必须有对象
Object obj = clazz.newInstance();
//使用父类的方法将访问权限检查能力取消。
field.setAccessible(true);//暴力访问。
field.set(obj, 40);
System.out.println(field.get(obj));
}
}
反射方法:
package heng.java.reflect.method;
import java.lang.reflect.Method;
public class ReflectMethodDemo {
public static void main(String[] args) {
try {
getMethodDemo();
getMethodDemo2();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//反射方法,静态,无参数的show方法。
private static void getMethodDemo2() throws Exception {
String className = "heng.java.reflect.constructor.Person";
Class clazz = Class.forName(className);
Method method = clazz.getMethod("staticShow", null);
method.invoke(null, null);
}
//反射方法,非静态,无参数的show方法。
public static void getMethodDemo() throws Exception {
String className = "heng.java.reflect.constructor.Person";
Class clazz = Class.forName(className);
Method method = clazz.getMethod("show", null);
Object obj = clazz.newInstance();
method.invoke(obj, null);
}
//反射方法,非静态,无参数的show方法。
public static void getMethodDemo3() throws Exception{
String className = "heng.java.reflect.constructor.Person";
Class clazz = Class.forName(className);
Method method = clazz.getMethod("paramShow", String.class,int.class);
Object obj = clazz.newInstance();
method.invoke(obj, "wangwu",22);
}
}
Person类:
package heng.java.reflect.constructor;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
System.out.println("Person run");
}
public void show(){
System.out.println("person show run");
}
public static void staticShow(){
System.out.println("person static show run");
}
public void paramShow(String name, int age){
System.out.println("show:"+name+"-----"+age);
}
}