首页 > 代码库 > java反射小例子
java反射小例子
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。