The Invoke method function in the method class in Java reflection

Source: Internet
Author: User

First, the method class represents a way, so invoke (call) is the method that calls the methods class representative. It allows you to implement dynamic invocation, such as you can dynamically transfer the parameters. The following is a simple example.

123456789101112131415161718192021222324252627282930313233343536 publicclassMethodTest{    publicstaticvoid main(String[] args)    {        String [] names ={"tom","tim","allen","alice"};        Class<?> clazz = Test.class;        try        {            Method method = clazz.getMethod("sayHi", String.class);            for(String name:names)                method.invoke(clazz.newInstance(),name);        catch(NoSuchMethodException e)        {            e.printStackTrace();        catch(IllegalAccessException e)        {            e.printStackTrace();        catch(IllegalArgumentException e)        {            e.printStackTrace();        catch(InvocationTargetException e)        {            e.printStackTrace();        catch (InstantiationException e)        {            e.printStackTrace();        }    }}classTest{    publicvoidsayHi(String name)    {        System.out.println("Hi "+name);    }}

The Invoke method function in the method class in Java reflection

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.