zoukankan      html  css  js  c++  java
  • Treflection02_getMethods()_getMethod()

    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、

  • 相关阅读:
    JS如何获取并操作iframe中的元素?
    CSS(14)元素定位
    C#基础 [01] 从Hello World 开始
    CSS(15)浮动
    C#基础 [05] 类和对象
    关于Visual Studio 2010 编辑器的一些设置
    Ext JS(1)Ext JS简介
    C#基础 [03] 类型和成员
    Python中基本数据类型的学习
    Python:集合与字符串格式化
  • 原文地址:https://www.cnblogs.com/javaskill/p/5428277.html
Copyright © 2011-2022 走看看