[Java]java反射随笔

来源:互联网 发布:海信电视看网络电视 编辑:程序博客网 时间:2024/06/06 00:57

      类是面向对象的灵魂,一切事物都可以以类来抽象。

     在java使用过程中,我们可能会经常用到一个反射的知识,只是别人都封装好的,如jdbc的加载驱动类有一句Class.for(“…jdbc…”).newInstance.当然框架也是离不开了反射,spring能这么方便也不例外。

     最新项目中需要再底层库(常用的操作,汇聚的库)用到应用库(在底层库上根据需求新建的库)中的一个类,本来想直接把这个类放到底层库里,一看,需要改动的太大,于是乎就想到了反射。

    至于反射,我们不得不提一个一个类那就是Class(不是class),位置为java.lang.Class。这是他的api中一些解释。

image

  闲话少说,针对刚才的问题怎么做呢?

  我们要知道需要传进来的类名吧,我们需要类里面的方法吧。 怎么获取呢?

  类么,我们可以直接来设置:

Class a = T.class;

怎么获取方法呢,哈哈,忘了刚才的APi了么?

image

可以获取函数,属性之类等等。

获取函数:

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中有个函数print(String str,int 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);}}
                                                                                                                                                                                                                                                                                                                                                                                                            
0 0
原创粉丝点击