首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

spring-java反照

2012-09-21 
spring--java反射package org.reflectpublic class Car {private String brandprivate String colorpri

spring--java反射
package org.reflect;

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 void introduce() {
System.out.println("brand:" + brand + ";color:" + color + ";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;
}

}
package org.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class ReflectTest {

public static Car  initByDefaultConst() throws Throwable{
//加载类加载器
ClassLoader loader = Thread.currentThread().getContextClassLoader();

//加载类
Class clazz = loader.loadClass("org.reflect.Car");

//构造器

Constructor con = clazz.getDeclaredConstructor((Class[])null);

//实例化

Car car = (Car) con.newInstance();

//把参数传到car中

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

public static Car initByParamConst()  throws Throwable{
//加载类加载器
ClassLoader loader = Thread.currentThread().getContextClassLoader();

Class clazz = loader.loadClass("org.reflect.Car");
//加载构造器
Constructor con = clazz.getDeclaredConstructor(new Class[]{String.class,String.class,int.class});


Car car = (Car) con.newInstance(new Object[]{"红旗CA73","白色",210});
return car;
}
public static void main(String[] args){

try {
ReflectTest.initByDefaultConst().introduce();
ReflectTest.initByParamConst().introduce();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

热点排行