码迷,mamicode.com
首页 > 编程语言 > 详细

java反射机制-简单实例

时间:2017-06-25 20:22:06      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:and   read   example   void   load   new   context   构造   反射   

public class Car {
private String brand;
private String color;
private int maxSpeed;

public Car() {
}

public Car(String brand, String color, int maxSpeed) {
this.brand = brand;
this.color = color;
this.maxSpeed = maxSpeed;
}

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;
}

public void introduce() {
System.out.println("brand:"+brand+";color:"+color+";maxspeed:"+maxSpeed);
}
}




//通过类加载器加载Car类对象
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class<?> clazz = loader.loadClass("com.example.demo.Test.Car");

//获取类的默认构造器并通过它实例化Car
Constructor cons = clazz.getDeclaredConstructor((Class[]) null);
Car car = (Car) cons.newInstance();


//通过反射方法设置属性
Method setBrand = clazz.getMethod("setBrand", String.class);
setBrand.invoke(car, "红旗CA72");
Method setColor = clazz.getMethod("setColor", String.class);
setColor.invoke(car, "黑色");
Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class);
setMaxSpeed.invoke(car, 200);
return car;

java反射机制-简单实例

标签:and   read   example   void   load   new   context   构造   反射   

原文地址:http://www.cnblogs.com/rzstrong/p/7077684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!