Invoke delegate for Java method

Source: Internet
Author: User

Invoke delegate for Java method

@author Ixenos

Class object run-time constructs and DelegateCalling methods (Method Class)

0. Dynamically constructs the corresponding type object from the class object

GetMethod method for 1.Class objects, constructed by method names and parameters

The invoke method of the 2.Method object to delegate the dynamically constructed corresponding type object so that it executes the corresponding parameter of the Add method

//Dynamic construction of an instance of the Invoketest class
Class<?> ClassType = invoketest.class; Object invoketest=classtype.newinstance ();//Dynamic constructionthe Add (int num1, int num2) method of the Invoketest class, which is marked as a Addmethod methods objectMethod Addmethod = Classtype.getmethod ("Add",Newclass[]{int.class,int.class});///Dynamic constructed method object invoke delegate dynamically constructed Invoketest object, execute corresponding parameter of Add method
Object result = Addmethod.invoke (Invoketest,NewObject[]{1, 2});//Test OutputSystem.out.println ((Integer) result);
 PublicMethod GetMethod (String name, Class<?>... parametertypes)throwsNosuchmethodexception, SecurityException Returns a method object that reflects the specified public member methods of the class or interface represented by this class object. The name parameter is a String that specifies the short name of the method you want. The Parametertypes parameter is an array of Class objects that identify the type of the method parameter in the order in which they are declared. If the parametertypes isNULL, it is processed by an empty array. If Name is"<init>;" or "<clinit>", the nosuchmethodexception is raised. Otherwise, the method to be reflected is determined by the following algorithm (set C as the class represented by this object): Search for any matching method in C. If no matching method is found, the class will be recursively called on the superclass of C1step algorithm. If in the first1no method is found in the step, search for a matching method in the hyper-interface of C. If such a method is found, the method is reflected. Find a matching method in class C: If C just declares a public method with the specified name and has exactly the same formal parameter type, it is the reflected method. If more than one such method is found in C, and the return type of one of the methods is special than the return type of the other method, the method is reflected, otherwise a method is selected. Note that there can be multiple matching methods in a class, because although the Java language prohibits a class from declaring multiple methods with the same signature but different return types, the Java virtual machine is not forbidden. This increases the flexibility of the virtual machine and can be used to implement a variety of language features. For example, you can use the bridge method to implement covariant returns, and the bridge method and the method that will be overridden will have the same signature, with different return types. brige See the Java Language Specification section8.2 and 8.4section. Parameter: Name-Method Name Parametertypes-The parameter list returns: The Method object that matches the specified name and Parametertypes is thrown: nosuchmethodexception-If no matching method is found, or the method is named "<init>" or "<clinit>"NullPointerException-If Name isNULLSecurityException-If there is a security manager s, and any one of the following conditions is true: Call S.checkmemberaccess ( This, Member.public) The class loader that denies access to the method caller differs from an ancestor of the class loader that is not also the current class, and the call to S.checkpackageaccess () denies access to the class's package
Api-class-getmethod
 Publicobject Invoke (Object obj, object ... args)throwsillegalaccessexception, IllegalArgumentException, InvocationTargetException to Band The specified object with the specified argument invokes the underlying method represented by this method object. Individual parameters are automatically unpacked to match the basic parameters, and both the basic and reference parameters are subject to the method invocation transformation. If the underlying method is static, the specified obj parameter can be ignored. This parameter can be aNULL. If the shape parameter required by the underlying method is0, the supplied args array can be a length of 0 orNULL. If the underlying method is an instance method, it is called using dynamic method lookup, which is recorded in Java Language specification, Second Edition15.12.4.4this should be done in the case of overrides that occur based on the runtime type of the target object. If the underlying method is static and the class declaring the method has not been initialized, it will be initialized. If the method completes normally, the value returned by the method is returned to the caller, and if the value is a base type, it is first wrapped appropriately in the object. However, if the type of the value is a set of basic types, the array element is not wrapped in the object, in other words, an array of the base type is returned. If the underlying method returns a type ofvoid, the call returnsNULL. Parameter: obj-the object from which to invoke the underlying method args-the parameter used for the method call returns: The result of using the parameter args to designate the method represented by the object on obj is thrown: illegalaccessexception-If this method object enforces Java language access control, the underlying method is inaccessible. IllegalArgumentException-If the method is an instance method, and the specified object parameter is not an instance of the class or interface (or the subclasses or the implementation program) that declares the underlying method, if the number of arguments and parameters is not the same, if the package conversion of the base parameter fails; You cannot convert a parameter value to the corresponding formal parameter type through a method call transformation. InvocationTargetException-if the underlying method throws an exception. NullPointerException-If the specified object isNULL, and the method is an instance method. Exceptionininitializererror-If the initialization caused by this method fails.
Api-method-invoke

Methods for obtaining copies of run-time objects with reflection (field Class)
1 ImportJava.lang.class;2 ImportJava.lang.reflect;3 4   Public classReflecttester5 {6      PublicObject copy (Object object)throwsException7 {8Class<?> ClassType =Object.getclass ();9Object objectcopy = Classtype.getconstructor (Newclass[]{}). newinstance (Newobject[]{});Ten       //get all member variables of an object Onefield[] Fields =classtype.getdeclaredfields (); A        for(Field field:fields) - { -String name =field.getname (); the         //converts the first letter of an attribute to uppercase -String Firstletter = name.substring (0,1). toUpperCase ();  -         //substring (1) represents the substring starting from index=1 to the last -String getmethodname = "Get" + Firstletter + name.substring (1); +String setmethodname = "Set" + Firstletter + name.substring (1); -Method GetMethod = Classtype.getmethod (Getmethodname,Newclass[] {}); +Method Setmethod = Classtype.setmethod (Getmethodname,Newclass[] {field.gettype ()}); AObject value = Getmethod.invoke (object,Newobject[] {}); atSetmethod.invoke (Objectcopy,Newobject[] {value}); - } -       returnobjectcopy; - } -      Public Static voidMain (string[] args) - { inCustomer customer =NewCustomer ("Tom", 20); -Customer.setid (1L); to  +Reflecttester test =NewReflecttester (); -Customer Customer2 =(Customer) test.copy (customer); theSystem.out.println (Customer2.getid () + "," + customer2.getname () + "," +customer2.getage ()); * } $ }Panax Notoginseng  - Class Customer the { +     Private floatID; A     PrivateString name; the     Private intAge ; +      PublicCustomer () - { $        This. ID = 1L; $        This. Name =A; -        This. Age = 1; - } the      PublicCustomer (String name,intAge ) - {Wuyi        This(); the        This. Name =name; -        This. Age =Age ; Wu } -      Public voidSetID (floatID) About { $        This. ID =ID; - } -}
View Code

0. Use class object to get corresponding type Object

1. Using the Getdeclaredfields method of the class object, get field[] Array

2. Traverse the field[] array, construct a string for each property name, capitalize the first letter, and then concatenate the get string to make the name of the setter and getter

3. At the same time, GetMethod, parameters are the method name and parameter type to be constructed, and get the setter and getter method object of each property.

4. At the same time, after the method is obtained, call the invoke delegate of each method object to execute the method of the corresponding type object (there is an argument passed in, or return value)

Invoke delegate for Java method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.