标签:
package com.reflect; /** * Created by gao on 16-3-18. */ public class ClassLoaderTest { public static void main(String[] args) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); System.out.println("current loader:" + loader); System.out.println("parent loader:" + loader.getParent()); System.out.println("grandparent loader:" + loader.getParent().getParent()); } }
输出结果:
package com.reflect; /** * Created by gao on 16-3-18. */ 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); } protected void drive(){ System.out.println("dirve private car! the color is:"+color); } }
3、创建测试类com.reflect.ReflectTest
package com.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Created by gao on 16-3-18. */ public class ReflectTest { public static Car initByDefaultConst() throws Throwable{ ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class clazz = loader.loadClass("com.reflect.Car"); Constructor cons = clazz.getDeclaredConstructor((Class[]) null); Car car = (Car)cons.newInstance(); Method setBrand = clazz.getMethod("setBrand",String.class); setBrand.invoke(car,"奥迪"); Method setColor = clazz.getMethod("setColor",String.class); setColor.invoke(car,"红色"); Method setMaxSpeed = clazz.getMethod("setMaxSpeed",int.class); setMaxSpeed.invoke(car,300); return car; } public static void main(String[] args) throws Throwable { Car car = initByDefaultConst(); car.introduce(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class clazz = loader.loadClass("com.reflect.Car"); Car car1 = (Car)clazz.newInstance(); Field colorFld = clazz.getDeclaredField("color"); colorFld.setAccessible(true); colorFld.set(car1, "白色"); Method dirveMtd = clazz.getDeclaredMethod("drive",(Class[])null); dirveMtd.setAccessible(true); dirveMtd.invoke(car1,(Object[])null); } }
标签:
原文地址:http://www.cnblogs.com/yangyquin/p/5292412.html