首页 > 学院 > 开发设计 > 正文

java反射几个方法

2019-11-14 11:55:46
字体:
来源:转载
供稿:网友
对于类Carpackage com.mychebao.zzm.entity;public class Car{PRivate String brand;private String color;private int maxSpeed;public Car(){ super();}public Car(String brand, String color, int maxSpeed){ super(); this.brand = brand; this.color = color; this.maxSpeed = maxSpeed;}public void introduce(){ System.out.println( "Car [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;}

} 反射

Class cls = Class.forName("com.mychebao.zzm.entity.Car");//动态加载类

或者

ClassLoader loader = Thread.currentThread().getContextClassLoader();//获得加载器Class cls = loader.loadClass("com.mychebao.zzm.entity.Car");//加载,感觉这个是个类的结构,包含所有东西就等着你拿起来用

构造函数

Constructor cons = cls.getDeclaredConstructor((Class[])null);//获取构造函数此处为无参的

实例化对象

Car car = (Car)cons.newInstance();//构造函数实例化Car或者Car car = (Car)cls.newInstance();//直接实例化

操作对象

Method setBrand = cls.getDeclaredMethod("setBrand", String.class);//获取参数是String的setBrand方法Method[] methods = cls.getMethods();//获取所有方法(public的)Method[] methods = cls.getDeclaredMethods();//获取所有方法setBrand.invoke(car, "碰碰车!");//对car对象执行这个方法String name=method.getName();//获取方法名Class[] types=method.getParameterTypes();//获取方法的参数类型Field colorFld = cls.getDeclaredField("color");//获取color属性无论公私colorFld.setaccessible(true);//设置为可操作,如果是私有属性设置为true后即可对其进行进一步操作,反射可以无视其private属性,破防呀colorFld.set(pCar, "黑");直接给属性赋值method.getAnnotation(Test.class);//方法是是否含有Test注解Class[] types = {String.class,int.class}; //参数是String和int的Method m = cls.getDeclaredMethod("name", types);//获取方法名是name参数是String和int的方法
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表