java反射

获取某个类的构造方法

  • Constructor getConstructor(Class[] params) 根据构造函数的参数,返回一个具体的具有public属性的构造函数
  • Constructor getConstructors() 返回所有具有public属性的构造函数数组
  • Constructor getDeclaredConstructor(Class[] params) 根据构造函数的参数,返回一个具体的构造函数(不分public和非public属性)
  • Constructor getDeclaredConstructors() 返回该类中所有的构造函数数组(不分public和非public属性)

获取成员方法

  • Method getMethod(String name, Class[] params) 根据方法名和参数,返回一个具体的具有public属性的方法
  • Method[] getMethods() 返回所有具有public属性的方法数组
  • Method getDeclaredMethod(String name, Class[] params) 根据方法名和参数,返回一个具体的方法(不分public和非public属性)
  • Method[] getDeclaredMethods() 返回该类中的所有的方法数组(不分public和非public属性)

获取成员属性

  • Field getField(String name) 根据变量名,返回一个具体的具有public属性的成员变量
  • Field[] getFields() 返回具有public属性的成员变量的数组
  • Field getDeclaredField(String name) 根据变量名,返回一个成员变量(不分public和非public属性)
  • Field[] getDelcaredField() 返回所有成员变量组成的数组(不分public和非public属性)

获取类注解

Annotation[] annotations = clazz.getAnnotations();

方法返回类型

 Type tp = method.getGenericReturnType();
if(tp instanceof ParameterizedType){
    tp =(ParameterizedType) method.getGenericReturnType();
}
// 返回类型名称
System.out.println(tp.getTypeName());

方法形参名字

//org.springframework.core.LocalVariableTableParameterNameDiscoverer
 LocalVariableTableParameterNameDiscoverer parameterNameDiscoverer =
          new LocalVariableTableParameterNameDiscoverer();
  String[] paramNames = parameterNameDiscoverer.getParameterNames(method);

形参类型

  Type[] parameterTypes = method.getGenericParameterTypes();

包扫描

获取jar中的class

  public static void getJarClass(JarFile jarFile, String filepath, Set<Class<?>> clazzs)
      throws IOException {
    List<JarEntry> jarEntryList = new ArrayList<JarEntry>();
    Enumeration<JarEntry> enumes = jarFile.entries();
    while (enumes.hasMoreElements()) {
      JarEntry entry = (JarEntry) enumes.nextElement();
      // 过滤出满足我们需求的东西
      if (entry.getName().startsWith(filepath) && entry.getName().endsWith(".class")) {
        jarEntryList.add(entry);
      }
    }
    for (JarEntry entry : jarEntryList) {
      String className = entry.getName().replace('/', '.');
      className = className.substring(0, className.length() - 6);
      try {
        clazzs.add(Thread.currentThread().getContextClassLoader().loadClass(className));
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
  }

获取文件中的class

public static void getFileClass(String packName, String filePath, Set<Class<?>> clazzs) {
    File dir = new File(filePath);
    if (!dir.exists() || !dir.isDirectory()) {
      System.out.println("包目录不存在!");
      return;
    }
    File[] dirFiles = dir.listFiles(new FileFilter() {
      public boolean accept(File file) {
        boolean acceptDir = file.isDirectory();// 接受dir目录
        boolean acceptClass = file.getName().endsWith(".class");// 接受class文件
        return acceptDir || acceptClass;
      }
    });
    for (File file : dirFiles) {
      if (file.isDirectory()) {
        getFileClass(packName + "." + file.getName(), file.getAbsolutePath(), clazzs);
      } else {
        String className = file.getName().substring(0, file.getName().length() - 6);
        try {
          Class<?> clazz =
              Thread.currentThread().getContextClassLoader().loadClass(packName + "." + className);
          clazzs.add(clazz);
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        }
      }
    }
 }

扫描指定包下的class

 public static Set<Class<?>> findFileClass(String packName) {
    Set<Class<?>> clazzs = new LinkedHashSet<Class<?>>();
    String packageDirName = packName.replace('.', '/');
    Enumeration<URL> dirs;
    try {
      dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
      while (dirs.hasMoreElements()) {
        URL url = dirs.nextElement();
        String protocol = url.getProtocol();
        if ("file".equals(protocol)) {// 扫描file包中的类
          String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
          getFileClass(packName, filePath, clazzs);
        } else if ("jar".equals(protocol)) {// 扫描jar包中的类
          JarFile jarFile = ((JarURLConnection) url.openConnection()).getJarFile();
          getJarClass(jarFile, packageDirName, clazzs);
        }
      }
    } catch (Exception e) {
      e.getStackTrace();
    }
    return clazzs;
 }