Java implements method call through reflection

Source: Internet
Author: User
  • Code Implementation
package me.andy.practice.reflect;import org.junit.Test;import java.lang.reflect.Constructor;import java.lang.reflect.Method;import static junit.framework.Assert.assertEquals;public class MethodInvokeTest {    @Test    public void test_add() throws Exception {        Class<?> personClass = Calculate.class;        Object person = personClass.newInstance();        Method method = personClass.getDeclaredMethod("add", new Class[]{int.class, int.class});        Object result = method.invoke(person, new Object[]{1, 2});        assertEquals(result, 3);    }    @Test    public void test_subtract() throws Exception {        Class<?> personClass = Calculate.class;        Object person = personClass.newInstance();        Method method = personClass.getDeclaredMethod("subtract", new Class[]{int.class, int.class});        method.setAccessible(true);        Object result = method.invoke(person, new Object[]{2, 1});        assertEquals(result, 1);    }}class Calculate {     public int add(int a, int b) {        return a + b;    }    private int subtract(int a, int b) {        return a - b;    }}

  • Code Description

Create object: Object person = personclass. newinstance ();

Method method = personclass. getmethod ("add", new class [] {Int. Class, Int. Class });

Method call: Object result = method. Invoke (person, new object [] {1, 2 });

Private access method: method. setaccessible (true );

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.