反射 与文件读写 泛型参数
最近公司项目需要根据bean生成对应的yaml配置文件,需要用到反射和文件操作,API总结如下:
文件读写:
File file = new File(path); file.isDirectory(); File[] files = file.listFiles(); String name = file1.getAbsolutePath(); name = file1.getName(); File file = new File(path + c.getSimpleName() + ".yaml"); if (file.exists()) { file.delete(); } file.createNewFile(); FileWriter fileWriter = new FileWriter(file); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write("definitions:"); bufferedWriter.newLine(); bufferedWriter.flush(); bufferedWriter.close();
反射:
Class c = Class.forName("model." + name); Field[] fields = c.getDeclaredFields(); Class c = field.getType(); field.getType().getSimpleName() //泛型参数 Type fieldType = field.getGenericType(); //获取对应的泛型类 Type type = ((ParameterizedType) fieldType).getActualTypeArguments()[0]; String name = type.getTypeName();