因为演示需要,所以把Person类尽量的造得尽可能的复杂,如下
Person类:
@MyAnnotation(value = "PeterLi") public class Person extends Creature<String> implements Comparable, MyInterface { public String name; private int age; int id; protected boolean sex; //创建类时,尽量保留一个空参的构造器 public Person() { // System.out.println("今天天气很闷热"); } public Person(String name) { this.name = name; } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @MyAnnotation(value = "abc123") public void show() { System.out.println("我是一个人!"); } private void display(String nation) throws Exception{ System.out.println("我的国籍是" + nation); } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override public int compareTo(Object o) { return 0; } class Bird{ } }
Creature父类:
public class Creature<T> { public double weight; public void breath() { System.out.println("呼吸"); } }
MyInterface接口:
public interface MyInterface extends Serializable { }
MyAnnotation注解:
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value(); }
下面是代码示例:
public class TestConstructor { @Test public void test1() throws Exception { String className = "com.peter.java19.Person"; Class clazz = Class.forName(className); //创建对应的运行时类的对象。使用newInstance()实际上就是调用了运行时的空参的构造器。 //要先想能够创建成功 1.要求对应的运行时类要有空参的构造器。 2.构造器的权限修饰符的权限要足够。 Object obj = clazz.newInstance(); Person p = (Person) obj; System.out.println(p); } @Test public void test2() throws ClassNotFoundException { String className = "com.peter.java19.Person"; Class clazz = Class.forName(className); Constructor[] cons = clazz.getDeclaredConstructors(); for (Constructor c : cons) { System.out.println(c); } } }
test1结果:
Person{name='null', age=0}
test2结果:
public com.peter.java19.Person(java.lang.String,int)
public com.peter.java19.Person(java.lang.String)
public com.peter.java19.Person()
关于构造器的其他就不演示了和属性与方法篇差不多