反射案例代码
点击查看代码
package com.bh.zoo;
public class Wolf extends Animal{
public String name;
public String color;
protected String blood;
private int age;
public void eat(){
System.out.println("狼吃肉");
}
public void eat(String food){
System.out.println("狼吃"+food);
}
private void sleep(){
System.out.println("sleep....");
}
}
点击查看代码
package com.bh.demo;
import com.bh.zoo.Wolf;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
System.out.println("start-----------");
//获得类对象,方法1
Class clz1=null;
try {
clz1 = Class.forName("com.bh.zoo.Wolf");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
//获得类的所有成员属性
//通过getFields方法获得是所有public的成员属性
/* Field[] fields = clz1.getFields();
for (int i = 0; i < fields.length; i++) {
Field f= fields[i];
System.out.println(f.getName());
}*/
// 通过getDeclaredFields方法,可以获得所有的成员属性
/* Field[] declaredFields = clz1.getDeclaredFields();
for (int i = 0; i < declaredFields.length; i++) {
System.out.println(declaredFields[i].getName());
}*/
//获得类对象,方法2(同1)
Class<Wolf> clz2 = Wolf.class;
/* Field[] fields = clz2.getFields();
for (int i = 0; i < fields.length; i++) {
Field f= fields[i];
System.out.println(f.getName());
}*/
//获得类对象,方法3
Wolf northWolf = new Wolf();
Class clz3 = northWolf.getClass();
/* Field[] fields = clz3.getFields();
for (int i = 0; i < fields.length; i++) {
Field f= fields[i];
System.out.println(f.getName());
}*/
/* Field[] declaredFields = clz3.getDeclaredFields();
for (int i = 0; i < declaredFields.length; i++) {
System.out.println(declaredFields[i].getName());}*/
//获得成员方法(包括父类)公共的
/* Method[] methods = clz2.getMethods();
for (Method m:methods) {
System.out.println(m.getName());
}*/
//获得成员方法(自己)
/* Method[] declaredMethods = clz2.getDeclaredMethods();
for (Method m:declaredMethods) {
System.out.println(m.getName());
}*/
Wolf w1 = null;
Wolf w2 = null;
Wolf w3 = null;
try {
w1 = (Wolf) clz2.newInstance();
w2 = (Wolf) clz2.newInstance();
w3 = (Wolf) clz2.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
//w1.eat();
w2.eat("草");
try {
//获取指定无参方法,通过w2对象调用
/*Method eatMethod = clz2.getMethod("eat", null);
eatMethod.invoke(w2,null);*/
//获取指定有参方法,通过w1对象赋值调用
Method eatMethod = clz2.getMethod("eat", String.class);
eatMethod.invoke(w1,"苹果");
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
System.out.println("end-----------");
}
}