最近有个朋友在做一个爬虫项目,问我是否可以考虑用Java代码动态生成一个Java文件!在我写完了之后,然后问他用这个来干啥,朋友很直接的说,存数据库,我当时的表情就是,日狗,你忙吧,我吃柠檬。。。好吧,下面我说一下思路:
其实说难不难,就这样用最蠢的方式写了一个代码!
原理就是自己生成代码,其实java里面自动生成代码的框架很多,例如JAVAssist,而我,为了简单思路,就直接用StringBuffer写!
- 使用Gson分析,Gson会生成一个解析对象LinkedTreeMap,而里面的Entity内部类保存着Gson的key-value键值对,其中value可能是LinkedTreeMap对象,也可能是其它数据类型,我们姑且用Object来代替
- 怎么去写这个类,首先肯定是写类名,然后写变量名
如果是基本数据类型和String,那么直接打印出来,变量名就是key值
如果是List类型,那么则需要导入ArrayList类型,然后取第一个数据,开始递归操作
如果是数组类型(在Gson的解析里面是LinkedTreeMap),那么就应该重新声明一个类,开始进行内部类的递归操作,并添加变量和变量名!
如此一步一步下去,直到判断所有变量都是基本数据类型|String|自定义类 - 使用java i/o操作,将StringBuffer对象写进文件。那么要把文件写到哪个地方去,idea编译器只认识自己识别的文件路径,所以file = getClass().getResource().getFile()+""+filename + ".java"
- 编译java文件,并使用urlClassLoader加载Class文件就可以了
代码如下:
<pre>
package com.marco.test;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
/**
-
Created by KdMobiB on 2017/7/11.
*/
public class Utils {
File file;//java文件的生成目录
String rootName;/**
- 开始解析Json数据
- @param jsonStr
- @return
*/
@SuppressWarnings("unchecked")
public HashMap<String, Object> getRootFromJson(String rootClass, String jsonStr) {
LinkedTreeMap a = new Gson().fromJson(jsonStr, LinkedTreeMap.class);
return getKidFromJson(rootClass, a, true);
}
public HashMap<String, Object> getListRootFromJson(String rootClass, String jsonStr) {
LinkedTreeMap a = new Gson().fromJson(jsonStr, LinkedTreeMap.class);
startChildArrayClass(rootClass);
return getKidFromJson(rootClass, a, false);
}/**
WRITE THE KIDCLASS
@param a
-
@return
*/
public HashMap<String, Object> getKidFromJson(String childClass, LinkedTreeMap a, boolean disable) {
if ((!rootName.equals(childClass)) && disable) {
startChildClass(childClass);
}HashMap<String, Object> maps = new HashMap<String, Object>();
Set<LinkedTreeMap.Entry<String, Object>> entry = a.entrySet();
Iterator<LinkedTreeMap.Entry<String, Object>> iterator = entry.iterator();
while (iterator.hasNext()) {
LinkedTreeMap.Entry<String, Object> stringObjectEntry = iterator.next();
String sk = stringObjectEntry.getKey();
Object sv = stringObjectEntry.getValue();
if (sv instanceof LinkedTreeMap) {
//如果TreeMap类型,代表数据还有分支,继续遍历下去
getKidFromJson(sk, (LinkedTreeMap) sv, true);
stopChildClass();
} else if (sv instanceof ArrayList) {
//如果是List类型,列表内的数据需要重新创建一个类
getListRootFromJson(sk, new Gson().toJson(((ArrayList) sv).get(0)));
stopChildClass();
} else {
//当判断不是数组类型或者列表类型,直接将key写入当前的类
sb.append("\t" + sv.getClass().getSimpleName() + " " + sk + ";\t\n");
addGetAndSet(sb, sk, sv.getClass().getSimpleName());
}
maps.put(sk, sv);
}
return maps;
}
StringBuilder sb = new StringBuilder("\r\n");
/**
- 开始
- @param root
*/
public void startFileWrite(String root) {
rootName = root;
file = new File(getClass().getResource("").getFile() + "/" + root + ".java");
sb.append(getClass().getPackage() + ";" + "\r\n");
sb.append("public class " + root + "{" + "\r\n");
}
/**
- 结束
*/
public void finishFileWrite() {
try {
FileWriter fw = new FileWriter(file);
sb.append("\r\n");
sb.append("}");
fw.write(sb.toString());
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void startChildClass(String childName) {
String childClass = childName + "Class";
sb.append("public " + childClass + " " + childName + ";\r\n");
sb.append("class " + childClass);
sb.append("{" + "\r\n");
}public void startChildArrayClass(String childName) {
addLibsImport("import java.util.ArrayList;");
String childClass = childName + "Class";
sb.append("public ArrayList<" + childClass + "> " + childName + ";\r\n");
sb.append("class " + childClass);
sb.append("{" + "\r\n");
}public void stopChildClass() {
sb.append("\r\n");
sb.append("}");
}/**
- 编写Java文件
- @param maps
*/
public void writeInJava(HashMap<String, Object> maps) {
Iterator<LinkedTreeMap.Entry<String, Object>> iterator = maps.entrySet().iterator();
while (iterator.hasNext()) {
LinkedTreeMap.Entry<String, Object> entry = iterator.next();
if (entry.getValue() instanceof LinkedTreeMap) return;
String key = entry.getKey();
String FieldType = entry.getValue().getClass().getSimpleName();
sb.append("\r\n\t");
sb.append("public " + FieldType + " " + key + ";");
sb.append("\r\n\t");
addGetAndSet(sb, key, FieldType);
}
}
public void addGetAndSet(StringBuilder sb, String name, String type) {
sb.append("\r\n\t");
sb.append("public void " + "set" + name);
sb.append("(" + type + " " + name + "1" + ")");
sb.append("{");
sb.append("\r\n\t\t");
sb.append("this." + name + "=" + name + "1" + ";");
sb.append("\r\n\t");
sb.append("}");sb.append("\r\n\t"); sb.append("public " + type + " " + "get" + name); sb.append("(" + ")"); sb.append("{"); sb.append("\r\n\t\t"); sb.append("return " + name + ";"); sb.append("\r\n\t"); sb.append("}"); sb.append("\r\n");
}
/**
- 编译生成的Java文件
*/
public void complie2Class() {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
Iterable units = fileMgr.getJavaFileObjects(file);
JavaCompiler.CompilationTask t = compiler.getTask(null, fileMgr, null, null, null, units);
t.call();
try {
fileMgr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
- 通过Url加载生成Class文件
- @param className
*/
public void loadClass(String className) {
String fileUrl = "file:/" + file.getParent();
System.out.println(fileUrl);
try {
URL[] urls = new URL[]{new URL(fileUrl)};
URLClassLoader ul = new URLClassLoader(urls, ClassLoader.getSystemClassLoader());
Class c = ul.loadClass(getClass().getPackage().getName() + "." + className);
System.out.println(c.newInstance().getClass().getName());
Object o = c.newInstance();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
- 添加第三方导包
*/
public void addLibsImport(String lib) {
String regex = getClass().getPackage() + ";" + "\r\n";
if (!sb.toString().contains(lib)) {
sb.insert(sb.indexOf(regex) + regex.length(), "\r\n" + lib + "\r\n");
}
}
}
</pre>
使用方式:
<pre>
package com.marco.test;
import com.google.gson.Gson;
import java.util.HashMap;
//1. 判断当前是否存在rootName相同类
//2.先写rootClass类
//3.判断是否需要创建新的类
/**
- Created by KdMobiB on 2017/7/11.
*/
public class Json2JavaObjcet {
static String jsonStr = "{" +
"animals:{" +
"dog:[" +
"{name:Rufus,breed:labrador,count:1,twoFeet:false}," +
"{name:Marty,breed:whippet,count:1,twoFeet:false}" +
"]," +
"cat:{name:Matilda}" +
"}" +
"}";
// static String jsonStr = "{cat:{name:Matilda}," +
// "dog:{name:Matilda}," +
// "elephant:{name:Matilda}}";
// static String jsonStr = "{" +
// "Id:[{name:myname},{name:myname}]," +
// "Name:Matilda," +
// "Age:52," +
// "Time:6" +
// "}";
public static void main(String args[]) {
Utils utils = new Utils();
String className = "RootName";
utils.startFileWrite(className);//开始启动
utils.getRootFromJson(className,jsonStr);
utils.finishFileWrite();
utils.complie2Class();//编译Java文件
utils.loadClass(className);//加载Class文件
System.out.println(utils.getClass().getPackage().getName());
}
}
</pre>