调用反射类的指定方法
生活随笔
收集整理的這篇文章主要介紹了
调用反射类的指定方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package org.entity;import java.lang.reflect.Method;/*** 本案例演示如何通過反射將字符串轉換為類* */
public class Test2_2 {public static void main(String[] args) {String user = "org.entity.User";//字符串是該類的全限定名try {Class clzz = Class.forName(user);Object classObj=clzz.newInstance();//將class類轉換為對象//--------------------反射類調用User中的sayHello()方法-----------------------------//注意導入正確的Method包名:// import java.lang.reflect.Method;//參數是StringMethod method = clzz.getMethod("sayHello",String.class);method.invoke(classObj, "Hello wold");//參數是其余基本數據類型/*Method method = clzz.getMethod("sayHello",int.class);method.invoke(classObj, 52);*///注入double類型Method method = clzz.getMethod("sayHello",double.class);/*Method method = clzz.getMethod("sayHello3",String[].class);String[] ss=new String[]{"1","2","3"};method.invoke(classObj, new Object[]{ss});*/} catch (ClassNotFoundException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();} }}
總結
以上是生活随笔為你收集整理的调用反射类的指定方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 紫光展锐完成Android 14同步升级
- 下一篇: 通过反射获取方法返回的类型