zoukankan      html  css  js  c++  java
  • java 反射类Method的使用

    package com.robert.reflect;
    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class InvokerTest 
    {
    	
    	public int add(int a, int b)
    	{
    		return a + b;
    	}
    	
    	public String echo(String str)
    	{
    		return "echo " + str;
    	}
    	
    	public static void main(String[] args)
    	{
    		Class classType = InvokerTest.class;
    		try {
    //			Object invokerTest = classType.newInstance();        //构造默认构造器
    			Object invokerTest = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
    			
    			Method addMethod = classType.getMethod("add", new Class[]{int.class,int.class});
    			Object result = addMethod.invoke(invokerTest, new Object[]{100,200});
    			System.out.println(result.toString());
    			
    			Method echoMethod = classType.getMethod("echo", new Class[]{String.class});
    			Object echoResult = echoMethod.invoke(invokerTest, new Object[]{"hello world"});
    			System.out.println(echoResult.toString());
    			
    		} catch (InstantiationException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} catch (SecurityException e) {
    			e.printStackTrace();
    		} catch (NoSuchMethodException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (InvocationTargetException e) {
    			e.printStackTrace();
    		}
    	}
    }
    

  • 相关阅读:
    2.5.4 使用popupWindow
    2.5.3 使用alertDialog创建自定义对话框
    2.5.2 使用alertdialog 创建列表对话框
    2.5.1 使用alertDialog
    2.4.12 画廊视图
    2.4.11 网格视图和图像切换器
    2.4.10 可展开的列表组件
    2.4.9 列表视图
    2.4.8 滚动视图
    2.4.7 选项卡的功能和用法
  • 原文地址:https://www.cnblogs.com/mengjianzhou/p/5986856.html
Copyright © 2011-2022 走看看