java 反射

package testGroupId;

/**
* Hello world!
*
*/
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

class Car {
private String brand;
private String color;
private int maxSpeed;
private String owner;//私有成员,没有对应的get和set方法;

//①默认构造函数
public Car(){}

//②带参构造函数
public Car(String brand,String color,int maxSpeed){
this.brand = brand;
this.color = color;
this.maxSpeed = maxSpeed;
}

//③未带参的方法
public void introduce() {
System.out.println("brand:"+brand+"; color:"+color+"; maxSpeed:" +maxSpeed);
}

//私有方法
private void whoHasIt(){
System.out.println("The owner of this car is:" + this.owner );
}

//参数的getter/Setter方法
public String getBrand() {
return brand;
}

public void setBrand(String brand) {
this.brand = brand;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

public int getMaxSpeed() {
return maxSpeed;
}

public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
}

class Test {
}


public class App
{
public static Car initByDefaultConst() throws Throwable
{
/**
* ①通过类装载器获取Car类对象
* 1.获取当前线程的ClassLoader
* 2.通过指定的全限定类“reflect.Car”装载Car类对应的反射实例
*/
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class class_car = loader.loadClass("testGroupId.Car");

/**
* ②获取类的默认构造器对象并通过它实例化Car
* 1.通过Car的反射类对象获取Car的构造函数对象cons
* 2.通过构造函数对象的newInstrance()方法实例化Car对象,其效果等同于new Car()
*/
Constructor cons = class_car.getDeclaredConstructor((Class[])null);
Car car = (Car)cons.newInstance();

/**
* ③获取类的成员变量(包含私有成员),并对成员变量赋值
*/
Field ownerFld = class_car.getDeclaredField("owner");
//取消Java语言访问检查以访问private变量
ownerFld.setAccessible(true);
ownerFld.set(car,"小明");


/**
* ④通过反射方法设置属性
* 通过Car的反射类对象的getMethod(String methodName,Class paramClass)获取属性的Setter方法对象,
* 第一个参数是目标Class的方法名;第二个参数是方法入参的对象类型。
*/
Method setBrand = class_car.getMethod("setBrand",String.class);
/**
* 通过invoke(Object obj,Object param)方法调用目标类的方法,
* 该方法的第一个参数是操作的目标类对象实例;第二个参数是目标方法的入参。
*/
setBrand.invoke(car,"红旗CA72");

Method setColor = class_car.getMethod("setColor", String.class);
setColor.invoke(car, "黑色");
Method setMaxSpeed = class_car.getMethod("setMaxSpeed",int.class);
setMaxSpeed.invoke(car, 200);

/**
* ⑤获取类的私有方法,并调用它
*/
Method whoHasItMtd = class_car.getDeclaredMethod("whoHasIt",(Class[])null);
//取消Java语言访问检查以访问private方法
whoHasItMtd.setAccessible(true);
whoHasItMtd.invoke(car,(Object[])null);

return car;
}

public static void main(String[] args) throws Throwable {
ClassLoader loader = Test.class.getClassLoader();
while (loader!=null){
System.out.println(loader);
loader = loader.getParent();
}
Car car = initByDefaultConst();
car.introduce();
}
}
posted @ 2017-05-08 10:00  穆穆兔兔  阅读(167)  评论(0编辑  收藏  举报