java Method 访问方法

在通过下列一组方法访问方法时,将返回Method类型的对象或数组。每个Method对象代表一个方法,利用Method对象可以操纵相应的方法。
 getMethods()
 getMethod(String name, Class<?>... parameterTypes)
 getDeclaredMethods()
 getDeclaredMethod(String name, Class<?>... parameterTypes)
如果是访问指定的方法,需要根据该方法的名称和入口参数的类型来访问。

/**
 * 
 */
package 访问方法;

/**
 * @author tianyu
 *
 */
public class Example_03 {

	static void staticMethod(){
		System.out.println("执行staticMethod()方法");
	}
	public int publicMethod(int i){
		System.out.println("执行staticMethod()方法");
		return i*100;
	}
	protected int protectedMethod(String s , int i) throws NumberFormatException{
		System.out.println("执行prottectedMethod()方法");
		return Integer.valueOf(s)+i;//字符串转型为string,返回Integer
	}
	@SuppressWarnings("unused")
	private String privateMethod(String ...strings){
		System.out.println("privateMethod()方法");
		StringBuffer buffer=new StringBuffer();
		for (int i = 0; i < strings.length; i++) {
			buffer.append(strings[i]);
		}
		return buffer.toString();//返回为Sting
	}
}



/**
 * 
 */
package 访问方法;

import java.lang.reflect.Method;


/**
 * @author tianyu
 *
 */
public class Main_03 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
	Example_03 example_03=new Example_03();
	Class<?> class1 =example_03.getClass();
	Method[] methods=class1.getDeclaredMethods();//获取所有的构造fangfa
		for (int i = 0; i < methods.length; i++) {
			Method method = methods[i];
		    System.out.println("获取方法名称:"+method.getName());//获取名称
			System.out.println("查看方法是否充许带有可变量参数"+method.isVarArgs());
			System.out.println("入口程序参数类型依次为");
			Class<?>[] classes=method.getParameterTypes();//获取这个函数的参数类型
			for (int j = 0; j < classes.length; j++) {
				Class<?> class2 = classes[j];
				System.out.println(class2);
			}
			System.out.println("返回值型为:"+method.getReturnType());	
			System.out.println("可能抛出的异常有:");
			Class<?>[] classes2=method.getExceptionTypes();
			for (int j = 0; j < classes2.length; j++) {
				Class<?> class2 = classes2[j];
				System.out.println("异常:"+class2);//有那些异常
			}
			boolean b=true;
			while(b){
				
				try {
					b=false;
					if("staticMethod".equals(method.getName())){
						//获取的方法名称去比较
						method.invoke(example_03);
					}else if("publicMethod".equals(method.getName())) {
						      
						System.out.println("返回值为:"+method.invoke(example_03, 168));
						
					}else if("protectedMethod".equals(method.getName())){
						System.out.println("返回值为:"+method.invoke(example_03, "7",5));
						
					}else if("privateMethod".equals(method.getName())){
						Object[] strings= new Object[]{new String[]{"m","q","e"}};
						System.out.println("返回值为:"+method.invoke(example_03,strings ));
					}
				} catch (Exception e) {
					System.out.println("在执行方法抛出异常,"
							+ "下面执行setAccessible()方法");
					method.setAccessible(true);
					b=true;
				}//异常
			
			}//while循环 	
			System.out.println("====================");
			
			
		}//for外循环

	}//主方发
}//类

	






猜你喜欢

转载自blog.csdn.net/qq_16555461/article/details/78563088