java反射調用方法
阿新 • • 發佈:2017-07-01
nbsp data- world dsm target cati ext getc 指定
參數: 返回: 該類與指定名和參數相匹配的方法的
參數: 返回: 使用參數
結果:
1:Class類中的方法
public Method getDeclaredMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
name
- 方法名parameterTypes
- 參數數組 Method
對象 2:Method類中的方法;
public Object invoke(Object obj, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException
obj
- 從中調用底層方法的對象args
- 用於方法調用的參數 args
在 obj
上指派該對象所表示方法的結果 3:hello world!級別的反射調用:
package com.dao.Text; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class TetsReflect { /** * @param args * @throws NoSuchMethodException * @throws SecurityException * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Person p = new Person(); Class cla = p.getClass(); // 1:無參數 Method method1 = cla.getDeclaredMethod("print"); method1.invoke(p); // 2:有參數的調用 Method method2 = cla.getDeclaredMethod("printParameter", String.class); method2.invoke(p, "hello world!!"); } } class Person { public void print() { System.out.println("hello world!!"+"沒有參數反射方法的調用"); } public void printParameter(String param) { System.out.println(param+"有參數的反射方法的調用"); } }
結果:
hello world!!沒有參數反射方法的調用
hello world!!有參數的反射方法的調用
java反射調用方法