Home > Java > javaTutorial > body text

Calling methods via Java reflection

高洛峰
Release: 2016-12-12 13:00:50
Original
1678 people have browsed it

Calling methods through Java reflection

This is an example for testing, calling the method of an object through reflection.

TestRef.java

import java.lang.reflect.Method; 
import java.lang.reflect.InvocationTargetException; 

/** 
* Created by IntelliJ IDEA. 
* File: TestRef.java 
* User: leizhimin 
* Date: 2008-1-28 14:48:44 
*/ 
public class TestRef { 

    public static void main(String args[]) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { 
        Foo foo = new Foo("这个一个Foo对象!"); 
        Class clazz = foo.getClass(); 
        Method m1 = clazz.getDeclaredMethod("outInfo"); 
        Method m2 = clazz.getDeclaredMethod("setMsg", String.class); 
        Method m3 = clazz.getDeclaredMethod("getMsg"); 
        m1.invoke(foo); 
        m2.invoke(foo, "重新设置msg信息!"); 
        String msg = (String) m3.invoke(foo); 
        System.out.println(msg); 
    } 
} 

class Foo { 
    private String msg; 

    public Foo(String msg) { 
        this.msg = msg; 
    } 

    public void setMsg(String msg) { 
        this.msg = msg; 
    } 

    public String getMsg() { 
        return msg; 
    } 

    public void outInfo() { 
        System.out.println("这是测试Java反射的测试类"); 
    } 
}
Copy after login

Console output result:

这是测试Java反射的测试类 
重新设置msg信息! 

Process finished with exit code 0
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template