首先我们在person包中新建一个Person.java:
package person; import sex.Sex; public class Person{ private String name = null; private int age = 0; private Sex sex = null; private String birthday = null; public Person(){}; public Person(String name, int age, Sex sex, String birthday){ String birMatch = "\\d{4}-\\d{2}-\\d{2}"; this.name = name; this.age = age; this.sex = sex; if(birthday.matches(birMatch)){ this.birthday = birthday; } } public void setInfo(String name, int age, Sex sex, String birthday){ String birMatch = "\\d{4}-\\d{2}-\\d{2}"; this.name = name; this.age = age; this.sex = sex; if(birthday.matches(birMatch)){ this.birthday = birthday; } } public String getPerName(){ return this.name; } public int getAge(){ return this.age; } public Sex getSex(){ return this.sex; } public String getBirthday(){ return this.birthday; } public String toString(){ return this.name + ", " + this.age + " years old, " + this.sex + ", " + this.birthday; } }
然后在sex包中建立一个枚举Sex.java:
package sex; public enum Sex{ MALE, FEMALE; }
再在main包的主方法取得Person类的完整结构:
package main; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import person.Person; import sex.Sex; public class Main { public static void main(String[] args){ try { Class<?> cls = Class.forName("person.Person"); //打开类 Field[] var = cls.getDeclaredFields(); //取得类的属性 Constructor<?>[] consMeth = cls.getConstructors(); //取得类的所有构造函数 Method[] meth = cls.getMethods(); //取得类的所有方法 for(int i=0; i<var.length; i++){ //输出属性 System.out.println(var[i].toGenericString()); } for(int i=0; i<consMeth.length; i++){ //输出构造函数 System.out.println(consMeth[i].toGenericString()); } for(int i=0; i<meth.length; i++){ //输出方法 System.out.println(meth[i].toGenericString()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
运行结果:
private java.lang.String person.Person.name private int person.Person.age private sex.Sex person.Person.sex private java.lang.String person.Person.birthday public person.Person() public person.Person(java.lang.String,int,sex.Sex,java.lang.String) public java.lang.String person.Person.toString() public sex.Sex person.Person.getSex() public java.lang.String person.Person.getPerName() public void person.Person.setInfo(java.lang.String,int,sex.Sex,java.lang.String) public int person.Person.getAge() public java.lang.String person.Person.getBirthday() public final void java.lang.Object.wait() throws java.lang.InterruptedException public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException public boolean java.lang.Object.equals(java.lang.Object) public native int java.lang.Object.hashCode() public final native java.lang.Class<?> java.lang.Object.getClass() public final native void java.lang.Object.notify() public final native void java.lang.Object.notifyAll()
结果说明该类继承得到的方法也可以得到。