1.得到类名:Class c = Class.forName(this.getClass().getName().toString()); this为instance,如果这句在基类,类,getClass会得到给子类。class name是包括包名的,比如com.vtasters.entity.Car Car是类名
2. 得到某类(this)的某属性:c.getField("location").get(this),如果该属性是static,就如下c.getField("location").get(null)
3. 设置某类(this)的某属性:c.getField("location").set(this, "Jersey city");
4. 获得某类某属性的类型:
Field fields[] = c.getDeclaredFields();
for(Field f : fields)
{
f.getType()
5. 调用方法:
Class cls=null;
cls=Class.forName("com.vtasters.Dish");
Object obj=cls.newInstance();
Method method=cls.getMethod("Test",null);
method.invoke(obj);
这里调用一个没有参数叫Test的方法
Class cls=null;
cls = Class.forName("com.framework.Action");
Object obj = cls.newInstance();
Class[] cArg = new Class[2];
cArg[0] = int.class;
cArg[1] = String.class;
Method method2 = cls.getMethod("bbb", cArg);
Object returnType = method2.getReturnType();
Object value = method2.invoke(obj,5,"6");
System.out.println(returnType.toString()+":"+value.toString());
这里调用一个带参数和返回值叫bbb的方法,定义如下
int bbb(int a, String b){}
注意,有时一些内部类带的属性或方法,不能在被调用的方法(e.g. bbb)中使用,要作为参数输入,否则会出现Reflection异常
如果参数个数是动态,就这样写:
String[] mainArgs = new String[5];
method.invoke(null, (Object)mainArgs);
getDeclaredMethod可以得到protected的方法,但getMethod只能得到公共方法
Class cls=null;
cls = Class.forName("com.framework.Action");
Object obj = cls.newInstance();
Class[] cArg = new Class[2];
cArg[0] = int.class;
cArg[1] = String.class;
Method method2 = cls.getMethod("bbb", cArg);
Object returnType = method2.getReturnType();
Object value = method2.invoke(obj,5,"6");
System.out.println(returnType.toString()+":"+value.toString());
这里调用一个带参数和返回值叫bbb的方法,定义如下
int bbb(int a, String b){}
注意,有时一些内部类带的属性或方法,不能在被调用的方法(e.g. bbb)中使用,要作为参数输入,否则会出现Reflection异常
如果参数个数是动态,就这样写:
String[] mainArgs = new String[5];
method.invoke(null, (Object)mainArgs);
getDeclaredMethod可以得到protected的方法,但getMethod只能得到公共方法
6. 返回值
Object value = method.invoke(this, x);
d = (Double) value;
7. 调用构造函数
cls = Class.forName("com.itg.generic.Events");
Class[] constructorArg = new Class[1];
constructorArg[0] = Operator.class;
Object obj = cls.getDeclaredConstructor(constructorArg).newInstance(this);
8. 判断一个数据是否实例
Num param instanceof Double
a=="mystr"不对,要用a.equals("mystr")
No comments:
Post a Comment