反射类及方法执行

来源:互联网 发布:flash mac破解版下载 编辑:程序博客网 时间:2024/05/16 11:36

前提:有这么一个实体类。
package com.example.test;

public Class Person
{
private int age;

public void setAge(int age)
{
this.age = age;
}

public int getAge()
{
return age;
}
}

1、Class<?> java.lang.Class.forName(String className) throws ClassNotFoundException

Class.forName("android.view.ScaleGestureDetector");

或可以定义接收对象Class<?> cl = Class.forName("com.example.test.Person");//?不用替换。

将返回  该类  对象。

Returns a Class object which represents the class with the given name. The name should be the name of a non-primitive class, as described in theclass definition. Primitive types can not be found using this method; useint.class orInteger.TYPE instead.

If the class has not yet been loaded, it is loaded and initialized first. This is done through either the class loader of the calling class or one of its parent class loaders. It is possible that a static initializer is run as a result of this call.

Throws
ClassNotFoundExceptionif the requested class can not be found.LinkageErrorif an error occurs during linkageExceptionInInitializerErrorif an exception occurs during static initialization of a class.  


2、Method java.lang.Class.getMethod(String name, Class... parameterTypes) throws NoSuchMethodExceptionSecurityException


3、Object java.lang.reflect.Method.invoke(Object receiver, Object... args) throwsIllegalAccessException,IllegalArgumentException,InvocationTargetException

Returns the result of dynamically invoking this method. Equivalent to receiver.methodName(arg1, arg2, ... , argN).

If the method is static, the receiver argument is ignored (and may be null).

If the method takes no arguments, you can pass (Object[]) null instead of allocating an empty array.

If you're calling a varargs method, you need to pass an Object[] for the varargs parameter: that conversion is usually done injavac, not the VM, and the reflection machinery does not do this for you. (It couldn't, because it would be ambiguous.)

Reflective method invocation follows the usual process for method lookup.

If an exception is thrown during the invocation it is caught and wrapped in an InvocationTargetException. This exception is then thrown.

If the invocation completes normally, the return value itself is returned. If the method is declared to return a primitive type, the return value is boxed. If the return type is void, null is returned.

Parameters
receiverthe object on which to call this method (or null for static methods)argsthe arguments to the method
Returns
  • the result
Throws
NullPointerExceptionif receiver == null for a non-static methodIllegalAccessExceptionif this method is not accessible (see AccessibleObject)IllegalArgumentExceptionif the number of arguments doesn't match the number of parameters, the receiver is incompatible with the declaring class, or an argument could not be unboxed or converted by a widening conversion to the corresponding parameter typeInvocationTargetExceptionif an exception was thrown by the invoked method 


Method method_setAge = cl.getMethod("setAge",new Class[]{ int.class });

method_setAge.invoke(new Person(),  { new Integer(25) });


Method method_getAge = cl.getMethod("getAge", null);

Integer age = method_getAge.invoke(new Person(),  null);


上面用到类的实例化对象时,用new Person()。另外还可以用class.newInstance();和constructor.newInstance();

关于这两者区别:

1、

尝试:通过Class.NewInstance()调用私有构造函数:

结果:通过Class.NewInstance()调用私有构造函数【失败】


尝试:通过Constructor.newInstance()调用私有构造函数:

结果:A's constructor is called.


2、class.newInstance调用无参构造。

constructor.newInstance()可调用含参构造。



0 0
原创粉丝点击