package com.tang;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class TestReflect {
public static Dog initByDefaultConst() throws Exception {
//1.通过类装载器获取Dog类对象
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class clazz = loader.loadClass("com.tang.Dog");
//2.获取类的默认构造器对象实例化Dog
Constructor<Dog> cons = clazz.getDeclaredConstructor((Class[])null);
Dog dog = cons.newInstance();
//3.通过反射方法设置属性
Method setColor = clazz.getMethod("setColor", String.class);
setColor.invoke(dog, "black");
Method setAge = clazz.getMethod("setAge", int.class);
setAge.invoke(dog, 2);
return dog;
}
@SuppressWarnings("unchecked")
public static Dog initByParaConst() throws Exception {
//1.通过类装载器获取Dog类对象
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class clazz = loader.loadClass("com.tang.Dog");
//2.获取类的默认构造器对象实例化Dog
Constructor<Dog> cons = clazz.getDeclaredConstructor(new Class[]{String.class,int.class});
Dog dog = cons.newInstance(new Object[]{"white",3});
return dog;
}
public static void main(String[] args) throws Exception {
System.out.println(initByDefaultConst().toString());
System.out.println(initByParaConst().toString());
}
}
package com.tang;
public class Dog {
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>private String color;
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>private int age;
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>public Dog(){
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>public Dog(String color,int age){
<span style="white-space:pre"> </span>this.setColor(color);
<span style="white-space:pre"> </span>this.setAge(age);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public void setColor(String color) {
<span style="white-space:pre"> </span>this.color = color;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public String getColor() {
<span style="white-space:pre"> </span>return color;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public void setAge(int age) {
<span style="white-space:pre"> </span>this.age = age;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>public int getAge() {
<span style="white-space:pre"> </span>return age;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>public String toString() {
<span style="white-space:pre"> </span>return "Dog [color=" + color + ", age=" + age + "]";
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>
}