`
kangsg219
  • 浏览: 121687 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

学习笔记之反射机制

阅读更多
Java反射机制具备的功能:

在运行时判断任意一个对象所属的类。
在运行时构造任意一个类的对象。
在运行时判断任意一个类所具有的成员变量和方法。
在运行时调用任意一个对象的方法

Reflection 是Java被视为动态(或准动态)语言的一个关键性质。这个机制允许程序在运行时透过Reflection APIs取得任何一个已知名称的class的内部信息,包括其modifiers(诸如public, static 等等)、superclass(例如Object)、实现之interfaces(例如Serializable),也包括fields和methods的所有信息,并可于运行时改变fields内容或调用methods


看例子:InvokeTest.java

package org.kangsg219.Reflection;

import java.lang.reflect.Method;

public class InvokeTest
{
    public int add(int a, int b)
    {
        return a + b;
    }

    public String hello(String username)
    {
        return "hello  " + username;
    }

    public static void main(String[] args) throws Exception
    {
       //正常调用
    	InvokeTest tester=new InvokeTest();
    	int addresult=tester.add(10, 20);
    	System.out.println(addresult);
    	String msg=tester.hello("kangsg219");
    	System.out.println(msg);
    	
    	//通过发射机制来调用
    	Class<?> classType = InvokeTest.class;
        Object invokeTest = classType.newInstance();
     
        // 调用InvokeTester对象的add()方法
        Method addMethod = classType.getMethod("add", new Class[] { int.class, int.class });
        Object result = addMethod.invoke(invokeTest, new Object[] { new Integer(10), new Integer(20) });
        System.out.println((Integer) result);

        // 调用InvokeTester对象的hello()方法
        Method echoMethod = classType.getMethod("hello", new Class[] { String.class });
        result = echoMethod.invoke(invokeTest, new Object[] { "kangsg219" });
        System.out.println((String) result);
    }
}


运行结果:

30
hello  kangsg219
30
hello  kangsg219
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics