做java开发也有一段时间了,一直以为自己对反射懂的比较多,可是今天却突然发现自己竟然这么基础的东西都不知道,不废话了,直接贴代码。
父类
package com.reflect;
public class Animal {
private String name;
/**
* @return the name
*/
public synchronized String getName() {
return name;
}
/**
* @param name the name to set
*/
public synchronized void setName(String name) {
this.name = name;
}
public Animal(String name) {
super();
this.name = name;
}
public Animal() {
super();
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Animal [name=" + name + "]";
}
}
子类
package com.reflect;
public class Cat extends Animal {
private int age;
/**
* @return the age
*/
public synchronized int getAge() {
return age;
}
/**
* @param age the age to set
*/
public synchronized void setAge(int age) {
this.age = age;
}
public Cat(int age) {
this.age = age;
}
public Cat() {
super();
// TODO Auto-generated constructor stub
}
public Cat(String name) {
super(name);
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Cat [age=" + age + "]";
}
}
测试类
package com.reflect;
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) {
Class clazz=Cat.class;
Cat cat=new Cat(15);
Field[] fields=clazz.getDeclaredFields();
for (Field field : fields) {
System.out.println(field.getName());
}
try {
Field field=clazz.getDeclaredField("name");
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(cat.getName());
}
}
结果
age
null
java.lang.NoSuchFieldException: name
at java.lang.Class.getDeclaredField(Class.java:1899)
at com.reflect.Test.main(Test.java:14)
其实父类和子类都有自己的字节码文件,子类的字节码是无法直接通过反射获取到父类的属性的,只能用子类的
clazz.getSuperClass.getDeclaredField(String filedName)方法来获取父类的属性,但是可以通过子类对象来操作父类的属性。