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

java反射小例子

时间:2014-07-01 22:14:33      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:blog   java   color   art   new   div   

package com.txwsqk.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 intruduce(){
		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 com.txwsqk.reflect;

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

public class CarTest {

	public static Car initByDefaultConst() throws Throwable{
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		Class<?> clazz = loader.loadClass("com.txwsqk.reflect.Car");
		Constructor<?> cons = clazz.getDeclaredConstructor((Class[])null);
		Car car = (Car) cons.newInstance();
		
		Method setBrand = clazz.getMethod("setBrand", String.class);
		setBrand.invoke(car, "BMW");
		Method setColor = clazz.getMethod("setColor", String.class);
		setColor.invoke(car, "red");
		Method setMaxspeed = clazz.getMethod("setMaxspeed", int.class);
		setMaxspeed.invoke(car, 150);
		return car;
		
	}
	public static void main(String[] args) throws Throwable {
		Car car = initByDefaultConst();
		car.intruduce();

	}

}

 输出:

brand BMW color: red maxspeed: 150

java反射小例子,布布扣,bubuko.com

java反射小例子

标签:blog   java   color   art   new   div   

原文地址:http://www.cnblogs.com/txwsqk/p/3816711.html

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