JAVA reflection mechanism, invoke invocation usage a small usage __java

Source: Internet
Author: User

Java Reflection Mechanism Basics:

Reference: http://lavasoft.blog.51cto.com/62575/43218/http://java.ccidnet.com/art/3539/20070924/1222147_1.html

Call to JAVA Invoke:

Like the next class

public class classa{
 private int Method1 (string[] strs) {
     int num=0;
     for (String str:strs)
          num++;
     return num;  
 }
}

Now we need to test the Method1 method in this class, and according to the Java reflection mechanism we can run this private method with the following code:

Class Ownerclass=classa.class;
Method method= Ownerclass.getdeclaredmethod ("Method1");
Method.setaccessible (true);
String[] strs= new string[]{"SSSs", "bbbb"};
ClassA classainstance= New ClassA ();
Method.invoke (Classainstance,strs);
An exception that produces a mismatch in the number of arguments is caused by the dynamic parameter matching of the Invoke function, which tells STRs to map to each parameter instead of an array variable, solution:

Class Ownerclass=classa.class;
Method method= Ownerclass.getdeclaredmethod ("Method1");
Method.setaccessible (true);
String[] strs= new string[]{"SSSs", "bbbb"};
Object[] Args=new object[1];
Args[0]=strs;
ClassA classainstance= New ClassA ();
Method.invoke (Classainstance,args);




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.