网站怎么发布做微商,个人网站空间申请,网站一次性链接怎么做,郑州百姓网免费发布信息类是面向对象的灵魂#xff0c;一切事物都可以以类来抽象。 在java使用过程中#xff0c;我们可能会经常用到一个反射的知识#xff0c;只是别人都封装好的#xff0c;如jdbc的加载驱动类有一句Class.for(“…jdbc…”).newInstance.当然框架也是离不开了反射#xff0c;s… 类是面向对象的灵魂一切事物都可以以类来抽象。 在java使用过程中我们可能会经常用到一个反射的知识只是别人都封装好的如jdbc的加载驱动类有一句Class.for(“…jdbc…”).newInstance.当然框架也是离不开了反射spring能这么方便也不例外。 最新项目中需要再底层库常用的操作汇聚的库用到应用库在底层库上根据需求新建的库中的一个类本来想直接把这个类放到底层库里一看需要改动的太大于是乎就想到了反射。 至于反射我们不得不提一个一个类那就是Class不是class位置为java.lang.Class。这是他的api中一些解释。 闲话少说针对刚才的问题怎么做呢 我们要知道需要传进来的类名吧我们需要类里面的方法吧。 怎么获取呢 类么我们可以直接来设置 Class a T.class; 怎么获取方法呢哈哈忘了刚才的APi了么 可以获取函数属性之类等等。 获取函数 public static Method getMethonName(Class? clazz,String methonName,Class?[] paramType) throws NoSuchMethodException, SecurityException {Method methon null;if(paramType null)methon clazz.getMethod(methonName,null);methon clazz.getMethod( methonName, paramType);L.p(methonName);return methon;} 来解释下如T中有个函数printString strint b获取这个函数呢可以通过以上函数来传参数 Class? clazz 对应的就是T记得带着包名 methon 就是字符”print”, Class?[] paramType就是那个括号里对应的参数java.lang.String和int.class Method method getMethonName(a, print, new Class?[] {int.class, String.class }); 函数的调用 Method method getMethonName(a, print, new Class?[] {int.class, String.class });Object o a.newInstance();method.invoke(o, 1, helllo); 注意事项 1 没有参数的就直接将paramType置为null 2 静态函数需要 Method method clazz.getMethod(methodName, pramTypes) 附下使用到的代码: package com.simple;import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;import com.cyning.log.L;public class TestReflect {public static void main(String[] args) {Class a T.class;Method[] methons a.getMethods();// for(Method m:methons){// L.p(m.getName());// L.p(m.getReturnType().toString());// m.setAccessible(true);// }try {Method method getMethonName(a, print, new Class?[] {int.class, String.class });Object o a.newInstance();method.invoke(o, 1, helllo);} catch (NoSuchMethodException | SecurityException e) {e.printStackTrace();}catch (InstantiationException | IllegalAccessException| IllegalArgumentException | InvocationTargetException e) {e.printStackTrace();}}public static Method getMethonName(Class? clazz, String methonName,Class?[] paramType) throws NoSuchMethodException,SecurityException {Method methon null;if (paramType null)methon clazz.getMethod(methonName, null);methon clazz.getMethod(methonName, paramType);L.p(methonName);return methon;}}class T {public void print(int a, String str) {System.out.println(a str);}
} 转载于:https://www.cnblogs.com/Cyning/p/3434207.html