package SBST2015; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.lang.reflect.* ; /** * Used to generate a stand-in class, which is used to test an abstract class. * An abstract class cannot be instantiated through its constructor, even if a * concrete constructor is provided. T3 can still instantiate it if it has a * creation method, else there is no way T3 can create an instance. * * A stand-in is a concrete class that simply extends an abstract class; so * instances of the abstract class can be created through its stand-in. */ public class StandInGeneratorCmd { static String mkStandInCode(Class abstractClass) throws Exception { String standinName = Common.mkSaveFileName(abstractClass.getName()) + "_StandIn" ; String s = "// a stand-in class for " + abstractClass + "\n"; s += "public class " + standinName + " extends " + abstractClass.getName() + "{\n" ; Constructor[] cons = abstractClass.getDeclaredConstructors() ; for (Constructor co : cons) { int flag = co.getModifiers() ; if (Modifier.isPublic(flag) || Modifier.isProtected(flag)) { Type[] tys = co.getGenericParameterTypes() ; s += " public " + standinName + "(" ; for (int k=0; k0) s += ", " ; s += tys[k].getTypeName() + " x" + k ; } s += ") throws Exception { " ; s += "super(" ; for (int k=0; k0) s += ", " ; s += "x" + k ; } s += ") ; }\n" ; } } s += "}" ; return s ; } /** * Save the content in the file, but if the file already exists, don't * over write! */ static private void saveButNotOverwrite(File file, String content) throws Exception { FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } /** * arg[0] : the full name of the abstract class whose stand-in must be created * arg[1] : the path to the src directory to put the stand-in * arg[2] : javac command to compile the generated class * * The standin is generated, but only saved if the file with the standin's name * does not exist yet. */ public static void main(String[] args) throws Exception { String absclassName = args[0] ; //String absclassName = "com.puppycrawl.tools.checkstyle.api.AbstractLoader" ; Class absclass = Class.forName(absclassName) ; if (! Modifier.isAbstract(absclass.getModifiers())) { // if it is not abstract, there is no need to create a stand-in return ; } String standInName = Common.mkSaveFileName(absclass.getName()) + "_StandIn" ; String srcpath = args[1] ; //String srcpath = "./src" ; String filename = srcpath + "/" + standInName + ".java" ; File file = new File(filename); if (file.exists()) return ; saveButNotOverwrite(file, mkStandInCode(absclass)) ; System.err.println("** a stand-in " + filename + " is created.") ; String compileCmd = args[2] + " " + filename ; System.err.println("** about to execute: " + compileCmd) ; Process p = Runtime.getRuntime().exec(compileCmd); p.waitFor(); System.err.println("** a stand-in " + filename + " is compiled.") ; } }