Java Reflection - Basic II

Find a method at runtime :

1. Class cls = obj.getClass();

2. Method meth = cls.getMethod ( "methodName", new Class[]{ "ParameterType".class } );


Here, if the "ParameterType" is "Class", then the type of "Parameter" can be represented by ParameterType.class. 

".class" literals  are Jave's way to specify a class object statically.

Then, what if the "ParameterType" is an array or an interface or a primitive type?

In java, we can also use ".class' literals to represent class objects for an array, interface or primitive.

e.g.

Method meth = Vector.class.getMethod ( "get", new Class[] {int.class} );

Method meth = Vector.class.getMethod( "addAll", new Class[] {Collection.class} );

Method meth = Vector.class.getMethod ( "copyTo", new Class[]{Object[].class});


Understanding Method Objects:

The same as we can use Class object to get the Name of Class(getName()) or get method of Class (getMethod()), we can get method related info from Method object.

e.g. the parameter augments , the return type, the exception type declared to be thrown by this method :

Class[] getExceptionTypes()

Class getReturnType()

Class[] getParameterTypes()

And there is a most important method in Method Class to consist of Reflection API : 

invoke(Object obj, Object[] args) : we can invoke one method of the obj object in argument with the args specified in  the parameter array args.

e.g.

The Dog Class has a method called " void yell(String words) ",  we can invoke it at runtime by following code:

Class cls =  Dog.class;

Method meth = cls.getMethod("yell",new Class[]{String.class});

metho.invoke(dog, "wangwangwang"); //here, think "dog" as an instance of Dog Class


Primitive Type as Parameter

If we have to pass a primitive as an argument or return a primitive as an output, we need to wrap it or unwrap it.

e.g.

Method meth =  obj.getMethod ("hashCode",null);

int hashcode=(Integer)(meth.invoke(obj,null)).intValue();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值