码迷,mamicode.com
首页 > 其他好文 > 详细

Treflection02

时间:2016-04-24 21:40:33      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

1、

package reflectionZ;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Treflection02
{
    public static void main(String[] args) throws Exception
    {
        // 第15课
        // getMethods()、getMethod()
        
        
        Class<?> clazz1 = Class.forName("reflectionZ.Cat");
        
        // 通过Class对象来得到构造函数
        Constructor<?> c2 = clazz1.getConstructor(String[].class);
        String[] foods = {"鱼", "老鼠"};
        //Cat cat2 = (Cat)c2.newInstance((Object)foods); // 强转
        //cat2.Show();
        
        Object obj = c2.newInstance((Object)foods);
        /*
        // 使用反射来调用 Show()
        // 获取 Show()方法
        // (1)、无参数
        Method method = clazz1.getMethod("Show");
        method.invoke(obj);
        //*/
        /*
        // (2)、无参数
        Method method = clazz1.getMethod("Show", null);
        method.invoke(obj, null);
        //*/
        /*
        // (3)、一个String参数
        Method method = clazz1.getMethod("Show", Class.forName("java.lang.String"));
        method.invoke(obj, "AA");
        //*/
        /*
        // (4)、两个参数: String + int
        Method method = clazz1.getMethod("Show", Class.forName("java.lang.String"));
        method.invoke(obj, "BB", 2);
        //*/
        /*
        // (5)、一个 List类型的参数
        Method method = clazz1.getMethod("Show", List.class);
        List list = new ArrayList();
        list.add("A01");
        list.add("A02");
        list.add("A03");
        method.invoke(obj, list);
        //*/
        //*
        // (6)、一个参数: int
        //    调用私有的函数
        Method method = clazz1.getDeclaredMethod("Show", int.class);
        method.setAccessible(true); // 暴力访问
        method.invoke(obj, 5);
        //*/
    }
}

 

2、

 

Treflection02

标签:

原文地址:http://www.cnblogs.com/javaskill/p/5428277.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!