调用反射类的指定方法
生活随笔
收集整理的這篇文章主要介紹了
调用反射类的指定方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
package org.entity;import java.lang.reflect.Method;/*** 本案例演示如何通過(guò)反射將字符串轉(zhuǎn)換為類* */
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類轉(zhuǎn)換為對(duì)象//--------------------反射類調(diào)用User中的sayHello()方法-----------------------------//注意導(dǎo)入正確的Method包名:// import java.lang.reflect.Method;//參數(shù)是StringMethod method = clzz.getMethod("sayHello",String.class);method.invoke(classObj, "Hello wold");//參數(shù)是其余基本數(shù)據(jù)類型/*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();} }}
總結(jié)
以上是生活随笔為你收集整理的调用反射类的指定方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 紫光展锐完成Android 14同步升级
- 下一篇: 通过反射获取方法返回的类型