问题
I am generating classes based on received JSON structures on the run time (using jsonschema2pojo).
1. Do we have to save a class as File in Java to be able to make use of it? currently, the class is being saved as follows:
codeModel.build(new File("src").getAbsoluteFile());
2. The goal is to check if the generated class (the body of the class or its file content) is the same as an already existed class file (with the same name) to skip saving that class. On the other hand, If the class' data has been updated and differs from the existed class, the new data will be overwritten.
in jsonschema2pojo
, a class will be generated and saved in a JCodeModel
object this way:
...
// Returns a JType:
mapper.generate(codeModel, className, "com.example", apiResultString);
// returned value: com.sun.codemodel.JDefinedClass(ClassName)
//Saves the generated class above, to a file:
codeModel.build(new File("src").getAbsoluteFile());
How could I extract a standard class out of JDefinedClass
to compare it with the existed class?
I tried the code below but it wasn't successful:
String str = String.valueOf(mapper.generate(codeModel, className, "com.example", apiResultString));
//str = com.sun.codemodel.JDefinedClass(ClassName)
String name = str.substring(str.indexOf("(")+1,str.indexOf(")"));
//name = ClassName
codeModel._getClass("com.example" + name);
// This also returns a JDefinedClass
The Class.forName()
might be useful to get the generated class which is saved in the JCodeModel
object (codeModel), I'm not sure how to this though.
3. What's the best way to compare those classes? A primary method would be to save the newly generated class as a file beside the existed class file, compare as two regular files in Java (using Checksum) and replace or remove the files accordingly. (This makes the whole process of getting the new class' content without saving it, nonsense) However, It's an unnecessary overhead I guess.
来源:https://stackoverflow.com/questions/56196669/compare-an-existed-class-file-with-a-jdefinedclass-content