List of usage examples for org.objectweb.asm Type getInternalName
public String getInternalName()
From source file:Java6to2.java
License:Open Source License
private static byte[] transform(InputStream classfile) throws IOException { ClassReader cr = new ClassReader(classfile); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); ClassVisitor cv = new ClassVisitor(ASM7, cw) { String internalName;// w ww . j a v a 2 s. co m boolean classLookupMethodGenerated; Set fieldsGenerated = new HashSet(); public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { /* Change class file version to 1.2 */ cv.visit(V1_2, access, name, signature, superName, interfaces); this.internalName = name; } /** * Generates the synthetic "class$" method, used to lookup classes via Class.forName(). This uses the exact same code as does JDK8 javac for target 1.2. */ void generateSyntheticClassLookupMethod() { MethodVisitor mv = cv.visitMethod(ACC_PRIVATE | ACC_STATIC | ACC_SYNTHETIC, "class$", "(Ljava/lang/String;)Ljava/lang/Class;", null, null); { Label start = new Label(); Label end = new Label(); Label handler = new Label(); mv.visitTryCatchBlock(start, end, handler, "java/lang/ClassNotFoundException"); mv.visitLabel(start); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;", false); mv.visitLabel(end); mv.visitInsn(ARETURN); mv.visitLabel(handler); mv.visitVarInsn(ASTORE, 1); mv.visitTypeInsn(NEW, "java/lang/NoClassDefFoundError"); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/NoClassDefFoundError", "<init>", "()V", false); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/NoClassDefFoundError", "initCause", "(Ljava/lang/Throwable;)Ljava/lang/Throwable;", false); mv.visitInsn(ATHROW); } mv.visitMaxs(2, 2); mv.visitEnd(); } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions); final ClassVisitor cv = this.cv; return new MethodVisitor(ASM7, mv) { /** * Intercepts class instantiations to see whether they instantiate a StringBuilder. Those instructions were generated by javac for string concatenations. But * StringBuilder is not available on JRE1.2, so we just replace it with StringBuffer. */ public void visitTypeInsn(int opcode, String type) { if (opcode == NEW && "java/lang/StringBuilder".equals(type)) { mv.visitTypeInsn(opcode, "java/lang/StringBuffer"); } else { mv.visitTypeInsn(opcode, type); } } /** * Intercepts method invocations to see whether they do something with StringBuilder. Those instructions were generated by javac for string concatenations. But * StringBuilder is not available on JRE1.2, so we just replace it with StringBuffer. */ public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if ("java/lang/StringBuilder".equals(owner)) { mv.visitMethodInsn(opcode, "java/lang/StringBuffer", name, desc.replace("java/lang/StringBuilder", "java/lang/StringBuffer"), itf); } else { mv.visitMethodInsn(opcode, owner, name, desc, itf); } } /** * Intercepts LDC instructions and check whether they are used to load a class. This is not supported on Java 1.2, so we convert it to the same code used by the * JDK8 javac: * <ul> * <li>create synthetic fields holding the resolved class objects * <li>create a synthetic method called "class$" which does Class.forName * </ul> */ public void visitLdcInsn(Object cst) { if (cst instanceof Type) { Type t = (Type) cst; String syntheticField = "class$" + t.getInternalName().replace('/', '$').replace("[", ""); if (!classLookupMethodGenerated) { /* Emit the synthetic "class$" method, used to lookup classes via Class.forName() */ generateSyntheticClassLookupMethod(); classLookupMethodGenerated = true; } if (!fieldsGenerated.contains(syntheticField)) { /* Generate a synthetic field holding the resolved Class object */ cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_SYNTHETIC, syntheticField, "Ljava/lang/Class;", null, null); fieldsGenerated.add(syntheticField); } mv.visitFieldInsn(GETSTATIC, internalName, syntheticField, "Ljava/lang/Class;"); Label nonNull = new Label(); mv.visitJumpInsn(IFNONNULL, nonNull); mv.visitLdcInsn(t.getInternalName().replace('/', '.')); mv.visitMethodInsn(INVOKESTATIC, internalName, "class$", "(Ljava/lang/String;)Ljava/lang/Class;", false); mv.visitInsn(DUP); mv.visitFieldInsn(PUTSTATIC, internalName, syntheticField, "Ljava/lang/Class;"); Label cnt = new Label(); mv.visitJumpInsn(GOTO, cnt); mv.visitLabel(nonNull); mv.visitFieldInsn(GETSTATIC, internalName, syntheticField, "Ljava/lang/Class;"); mv.visitLabel(cnt); } else { mv.visitLdcInsn(cst); } } }; } }; cr.accept(cv, ClassReader.SKIP_FRAMES); // <- Frames are not used in Java 1.2, so skip them return cw.toByteArray(); }
From source file:analysis.ReferenceGenerator.java
License:Open Source License
private void addTypeClassRef(Type type) { if (type.getSort() == Type.OBJECT) { addClassRef(type.getInternalName()); } }
From source file:blue.origami.asm.OClassWriter.java
License:Apache License
OClassWriter(OClassDecl cdecl) {
super(ClassWriter.COMPUTE_FRAMES);
// super(ClassWriter.COMPUTE_MAXS);
this.cname = cdecl.getName().replace(".", "/");
Type superType = cdecl.getSupertype().asmType();
String[] inames = null;//from w ww . j a v a 2 s . c o m
OType[] inf = cdecl.getInterfaces();
if (inf.length > 0) {
inames = new String[inf.length];
map(inf, inames, t -> t.asmType().getInternalName());
}
this.visit(V1_8, cdecl.getAnno().acc(), this.cname, cdecl.getSignature(), superType.getInternalName(),
inames);
this.visitSource(cdecl.getSourceName(), null);
this.cdecl = cdecl;
}
From source file:ca.oson.json.util.ObjectUtil.java
License:Open Source License
/** * Returns a list containing one parameter name for each argument accepted * by the given constructor. If the class was compiled with debugging * symbols, the parameter names will match those provided in the Java source * code. Otherwise, a generic "arg" parameter name is generated ("arg0" for * the first argument, "arg1" for the second...). * * This method relies on the constructor's class loader to locate the * bytecode resource that defined its class. * * @param constructor the constructor to get a list of parameter names * @return a list of parameter names/* w w w. j a v a 2 s . c o m*/ * @throws IOException io exception to throw */ private static List<String> getParameterNamesBytecode(Constructor<?> constructor) throws IOException { Class<?> declaringClass = constructor.getDeclaringClass(); ClassLoader declaringClassLoader = declaringClass.getClassLoader(); if (declaringClassLoader == null) { return null; } org.objectweb.asm.Type declaringType = org.objectweb.asm.Type.getType(declaringClass); String constructorDescriptor = org.objectweb.asm.Type.getConstructorDescriptor(constructor); String url = declaringType.getInternalName() + ".class"; InputStream classFileInputStream = declaringClassLoader.getResourceAsStream(url); if (classFileInputStream == null) { // throw new IllegalArgumentException("The constructor's class loader cannot find the bytecode that defined the constructor's class (URL: " + url + ")"); return null; } ClassNode classNode; try { classNode = new ClassNode(); ClassReader classReader = new ClassReader(classFileInputStream); classReader.accept(classNode, 0); } finally { classFileInputStream.close(); } @SuppressWarnings("unchecked") List<MethodNode> methods = classNode.methods; for (MethodNode method : methods) { if (method.name.equals("<init>") && method.desc.equals(constructorDescriptor)) { org.objectweb.asm.Type[] argumentTypes = org.objectweb.asm.Type.getArgumentTypes(method.desc); List<String> parameterNames = new ArrayList<String>(argumentTypes.length); @SuppressWarnings("unchecked") List<LocalVariableNode> localVariables = method.localVariables; for (int i = 0; i < argumentTypes.length && i < localVariables.size() - 1; i++) { // The first local variable actually represents the "this" object parameterNames.add(localVariables.get(i + 1).name); } return parameterNames; } } return null; }
From source file:ca.weblite.asm.ASMClassLoader.java
public ClassNode findClass(Type type) { if (nodeCache.containsKey(type.getInternalName())) { return nodeCache.get(type.getInternalName()); }/*from w w w . j a v a 2s. c o m*/ String classFile = type.getInternalName() + ".class"; while (true) { InputStream bytecode = loader.getResourceAsStream(classFile); if (bytecode != null) { try { ClassNode node = new ClassNode(); ClassReader reader = new ClassReader(bytecode); reader.accept(node, ClassReader.SKIP_CODE); if ((node.name + ".class").equals(classFile)) { nodeCache.put(type.getInternalName(), node); return node; } } catch (IOException ex) { Logger.getLogger(ASMClassLoader.class.getName()).log(Level.SEVERE, null, ex); } } int lastSlash = classFile.lastIndexOf("/"); if (lastSlash == -1) { break; } classFile = classFile.substring(0, lastSlash) + "$" + classFile.substring(lastSlash + 1); } return super.findClass(type); }
From source file:ca.weblite.asm.JavaExtendedStubCompiler.java
License:Apache License
public Map<String, byte[]> compile(List<Type> types, File sourceFile) throws IOException { final Map<String, byte[]> outMap = new HashMap<>(); final Set<String> typeNames = (types == null) ? null : new HashSet<String>(); if (types != null) { for (Type type : types) { typeNames.add(type.getInternalName()); }// w ww .j a v a 2s. co m } JavaCompiler compiler = JavacTool.create(); MyFileObject[] fos = new MyFileObject[] { new MyFileObject(sourceFile) }; JavacTask task = (JavacTask) compiler.getTask(null, null, null, null, null, Arrays.asList(fos)); Iterable<? extends CompilationUnitTree> asts = task.parse(); TreePathScanner scanner; final LinkedList<ClassFinder> scopeStack = new LinkedList<>(); scanner = new TreePathScanner() { String packageName; ClassNode superClass; LinkedList<String> stack = new LinkedList<>(); LinkedList<ClassInfo> classInfoStack = new LinkedList<>(); LinkedList<ClassWriter> cwStack = new LinkedList<>(); LinkedList<List<? extends TypeParameterTree>> typeParametersStack = new LinkedList<>(); @Override public Object visitCompilationUnit(CompilationUnitTree cut, Object p) { packageName = cut.getPackageName().toString(); ClassFinder scope = new ClassFinder(context.get(ClassLoader.class), null); scopeStack.push(scope); scope.addImport(packageName + ".*"); return super.visitCompilationUnit(cut, p); } private String getThisInternalName(String simpleName) { simpleName = simpleName.replaceAll("\\.", "$"); StringBuilder sb = new StringBuilder(); Iterator<String> it = stack.descendingIterator(); sb.append(packageName.replaceAll("\\.", "/")); sb.append("/"); while (it.hasNext()) { sb.append(it.next()).append("$"); } sb.append(simpleName); return sb.toString(); } @Override public Object visitImport(ImportTree it, Object p) { if (!it.isStatic()) { String path = it.getQualifiedIdentifier().toString(); scopeStack.peek().addImport(path); } return super.visitImport(it, p); } Object visitConstructor(final MethodTree mt, Object p) { ClassWriter classWriter = cwStack.peek(); List<Type> argTypes = new ArrayList<Type>(); boolean isVarArgs = false; for (VariableTree v : mt.getParameters()) { if (v.toString().endsWith("... " + v.getName())) { isVarArgs = true; } String type = v.getType().toString(); String fullType = type; String signature = null; try { signature = TypeUtil.getTypeSignature(type, scopeStack.peek()); } catch (Throwable t) { System.out.println("Failed to find signature for type"); } if (type.indexOf("<") != -1) { type = type.substring(0, type.indexOf("<")); } int dim = 0; if (TypeUtil.isArrayType(type)) { dim = TypeUtil.getArrayTypeDimension(type); type = TypeUtil.getArrayElementType(type); } if (TypeUtil.isPrimitiveType(type)) { String descriptor = TypeUtil.getDescriptor(type); argTypes.add(Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim))); } else { ClassNode stub = scopeStack.peek().findStub(type); assert stub != null; argTypes.add(Type.getObjectType(stub.name)); } } String methodDescriptor = null; String methodSignature = null; if (argTypes.isEmpty()) { methodDescriptor = Type.getMethodDescriptor(Type.getType("V")); } else { methodDescriptor = Type.getMethodDescriptor(Type.getType("V"), argTypes.toArray(new Type[0])); } int flags = getFlags(mt.getModifiers().getFlags()); if (isVarArgs) { flags |= Opcodes.ACC_VARARGS; } classWriter.visitMethod(flags, mt.getName().toString(), methodDescriptor, null, null); classInfoStack.peek().numConstructors++; return null; } @Override public Object visitMethod(MethodTree mt, Object p) { if (mt.getReturnType() == null) { // It's a constructor return visitConstructor(mt, p); } else { boolean isVarArgs = false; ClassWriter classWriter = cwStack.peek(); List<Type> argTypes = new ArrayList<>(); List<String> sigArgTypes = new ArrayList<>(); for (VariableTree v : mt.getParameters()) { String type = v.getType().toString(); if (v.toString().endsWith("... " + v.getName())) { isVarArgs = true; } sigArgTypes.add(type); int dim = 0; if (TypeUtil.isArrayType(type)) { dim = TypeUtil.getArrayTypeDimension(type); type = TypeUtil.getArrayElementType(type); } if (TypeUtil.isPrimitiveType(type)) { String descriptor = TypeUtil.getDescriptor(type); argTypes.add(Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim))); } else { if (isGenericType(type)) { type = "Object"; } int arrowPos = type.indexOf("<"); if (arrowPos != -1) { type = type.substring(0, arrowPos); } ClassNode stub = scopeStack.peek().findStub(type); if (stub == null) { throw new RuntimeException("Could not find class for " + type); } Type argType = Type.getObjectType(stub.name); argType = Type.getType(TypeUtil.getArrayDescriptor(argType.getInternalName(), dim)); argTypes.add(argType); } } String returnType = mt.getReturnType().toString(); if (isGenericType(returnType)) { returnType = "Object"; } String methodSignature = null; try { methodSignature = TypeUtil.getMethodSignature(scopeStack.peek(), returnType, sigArgTypes.toArray(new String[0])); } catch (Exception ex) { System.out.println( "Failed to get signature for method " + mt + " message: " + ex.getMessage()); } int dim = 0; Type returnTypeType = null; if (TypeUtil.isArrayType(returnType)) { dim = TypeUtil.getArrayTypeDimension(returnType); returnType = TypeUtil.getArrayElementType(returnType); if (isGenericType(returnType)) { returnType = "Object"; } } if (TypeUtil.isPrimitiveType(returnType)) { String descriptor = TypeUtil.getDescriptor(returnType); returnTypeType = Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim)); } else { int arrowPos = returnType.indexOf("<"); if (arrowPos != -1) { returnType = returnType.substring(0, arrowPos); } ClassNode stub = scopeStack.peek().findStub(returnType); if (stub == null) { System.out.println("Type params is " + mt.getTypeParameters()); System.out.println("Type kind is " + mt.getReturnType().getKind()); throw new RuntimeException("Could not find class for " + returnType); } returnTypeType = Type.getObjectType(stub.name); returnTypeType = Type .getType(TypeUtil.getArrayDescriptor(returnTypeType.getInternalName(), dim)); } String methodDescriptor = null; if (argTypes.isEmpty()) { methodDescriptor = Type.getMethodDescriptor(returnTypeType); } else { methodDescriptor = Type.getMethodDescriptor(returnTypeType, argTypes.toArray(new Type[0])); } int flags = getFlags(mt.getModifiers().getFlags()); if (isVarArgs) { flags |= Opcodes.ACC_VARARGS; //System.out.println("VarArgs "+flags); } classWriter.visitMethod(flags, mt.getName().toString(), methodDescriptor, methodSignature, null); } //methodStack.push(mt); //Object out= super.visitMethod(mt, p); //methodStack.pop(); return null; } //private boolean LinkedList<MethodTree> methodStack =new LinkedList<>(); @Override public Object visitVariable(VariableTree vt, Object p) { ClassWriter classWriter = cwStack.peek(); String varType = vt.getType().toString(); if (isGenericType(varType)) { varType = "Object"; } String signature = null; try { signature = TypeUtil.getTypeSignature(varType, scopeStack.peek()); } catch (Exception ex) { System.out.println("Failed to generate signature for type " + varType); } int dim = 0; Type varTypeType = null; if (TypeUtil.isArrayType(varType)) { dim = TypeUtil.getArrayTypeDimension(varType); varType = TypeUtil.getArrayElementType(varType); } if (TypeUtil.isPrimitiveType(varType)) { String descriptor = TypeUtil.getDescriptor(varType); varTypeType = Type.getType(TypeUtil.getArrayDescriptor(descriptor, dim)); } else { int arrowPos = varType.indexOf("<"); if (arrowPos != -1) { varType = varType.substring(0, arrowPos); } ClassNode stub = scopeStack.peek().findStub(varType); if (stub == null) { throw new RuntimeException("Could not find class for " + varType); } varTypeType = Type.getObjectType(stub.name); varTypeType = Type.getType(TypeUtil.getArrayDescriptor(varTypeType.getInternalName(), dim)); } classWriter.visitField(getFlags(vt.getModifiers().getFlags()), vt.getName().toString(), varTypeType.toString(), signature, null); return super.visitVariable(vt, p); //To change body of generated methods, choose Tools | Templates. } boolean isGenericType(String type) { for (List<? extends TypeParameterTree> types : typeParametersStack) { for (TypeParameterTree tree : types) { if (type.equals(tree.getName().toString())) { return true; } } } return false; } /** * Converts modifier flags from Javac Tree into int flags usable in * TypeMirror * @param mods * @return */ int getFlags(Set<Modifier> mods) { int flags = 0; for (Modifier m : mods) { switch (m) { case ABSTRACT: flags |= Opcodes.ACC_ABSTRACT; break; case FINAL: flags |= Opcodes.ACC_FINAL; break; case PRIVATE: flags |= Opcodes.ACC_PRIVATE; break; case PROTECTED: flags |= Opcodes.ACC_PROTECTED; break; case PUBLIC: flags |= Opcodes.ACC_PUBLIC; break; case STATIC: flags |= Opcodes.ACC_STATIC; break; } } return flags; } @Override public Object visitClass(ClassTree ct, Object p) { //System.out.println("Visiting class "+ct); //System.out.println("Type parameters: "+ct.getTypeParameters()); typeParametersStack.push(ct.getTypeParameters()); String simpleName = ct.getSimpleName().toString(); String internalName = getThisInternalName(simpleName); int lastDollar = internalName.lastIndexOf("$"); String externalName = lastDollar == -1 ? null : internalName.substring(0, lastDollar); String supername = "java.lang.Object"; String[] interfaces = null; boolean targetClass = false; if (!cwStack.isEmpty()) { cwStack.peek().visitInnerClass(internalName, externalName, simpleName, getFlags(ct.getModifiers().getFlags())); } targetClass = true; // This is the one that we' //String supername = "java.lang.Object"; if (ct.getExtendsClause() != null) { supername = ct.getExtendsClause().toString().trim(); } String unresolvedSuperName = supername; int bracketPos = supername.indexOf("<"); supername = bracketPos == -1 ? supername : supername.substring(0, bracketPos); ClassNode node = scopeStack.peek().findStub(supername); if (node == null) { throw new RuntimeException("Could not find super stub " + supername); } supername = node.name; String impl = ct.getImplementsClause().toString(); String[] unresolvedInterfaces = null; if (impl != null && !"".equals(impl)) { interfaces = impl.split(","); unresolvedInterfaces = new String[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { String iface = interfaces[i]; unresolvedInterfaces[i] = interfaces[i]; iface = iface.trim(); ClassNode inode = scopeStack.peek().findStub(iface); assert inode != null; if (inode == null) { throw new RuntimeException("Could not find stub for interface " + iface); } System.out.println("interface " + iface); interfaces[i] = inode.name; } } String signature = TypeUtil.getClassSignature(scopeStack.peek(), null, unresolvedSuperName, unresolvedInterfaces); int flags = getFlags(ct.getModifiers().getFlags()); switch (ct.getKind()) { case INTERFACE: flags |= Opcodes.ACC_INTERFACE; break; case ENUM: flags |= Opcodes.ACC_ENUM; break; } ClassWriter classWriter = new ClassWriter(49); classWriter.visit(49, flags, internalName, signature, supername, interfaces ); cwStack.push(classWriter); classInfoStack.push(new ClassInfo()); stack.push(simpleName); ClassFinder scope = new ClassFinder(context.get(ClassLoader.class), scopeStack.peek()); scope.addImport(internalName.replaceAll("/", ".").replaceAll("\\$", ".") + ".*" ); scope.addImport(internalName.replaceAll("/", ".").replaceAll("\\$", ".")); scope.addImport(supername.replaceAll("/", ".").replaceAll("\\$", ".") + ".*" ); scope.addImport(supername.replaceAll("/", ".").replaceAll("\\$", ".")); if (interfaces != null) { for (int i = 0; i < interfaces.length; i++) { scope.addImport(interfaces[i].replaceAll("/", ".").replaceAll("\\$", ".") + ".*" ); scope.addImport(interfaces[i].replaceAll("/", ".").replaceAll("\\$", ".")); } } for (TypeParameterTree tpTree : ct.getTypeParameters()) { //System.out.println("Name: "+tpTree.getName()); //System.out.println("Kind: "+tpTree.getKind().name()); //System.out.println("Bounds: "+tpTree.getBounds()); String bounds = (tpTree.getBounds() != null && !tpTree.getBounds().isEmpty()) ? tpTree.getBounds().get(0).toString() : "java.lang.Object"; scope.addTypeParameter(tpTree.getName().toString(), bounds); } scopeStack.push(scope); Object out = super.visitClass(ct, p); stack.pop(); scopeStack.pop(); ClassInfo classInfo = classInfoStack.pop(); if (classInfo.numConstructors == 0) { // there are no declared constructors in this class // we need to add a default constructor. cwStack.peek().visitMethod(Opcodes.ACC_PUBLIC, "<init>", Type.getMethodDescriptor(Type.getType("V")), null, null); classInfo.numConstructors++; } if (targetClass) { byte[] bytes = cwStack.peek().toByteArray(); outMap.put(internalName, bytes); cwStack.pop(); } typeParametersStack.pop(); return out; } }; scanner.scan(asts, null); return outMap; }
From source file:ca.weblite.asm.JavaExtendedStubCompiler.java
License:Apache License
public byte[] compile(final Type type, File sourceFile) throws IOException { Map<String, byte[]> out = compile(Collections.singletonList(type), sourceFile); return out.get(type.getInternalName()); }
From source file:ca.weblite.asm.JavaSourceClassLoader.java
@Override public ClassNode findStub(Type type) { String classFile = type.getInternalName() + ".class"; ClassNode cached = cacheClassLoader.findClass(type); long cacheMtime = cacheClassLoader.getLastModified(); String javaFile = type.getInternalName().replaceAll("\\$", "/") + ".java"; while (true) { File file = loader.getResource(javaFile); if (file != null) { try { if (cached != null && cacheMtime >= lastModified) { // The cached version is up to date // no need to load the class //System.out.println("Using cached version of "+classFile); return cached; }// ww w. j av a 2 s. c o m //System.out.println("Finding stub "+classFile); if (stubCache.containsKey(type.getInternalName())) { //System.out.println("Found in stub cache"); return stubCache.get(type.getInternalName()); } if (!parsedFiles.contains(javaFile)) { // This java file has already been parsed and it wasn't // in the stub cache parsedFiles.add(javaFile); Set<ClassNode> stubs = new JavaStubFactory(getContext()).createStubs(file); for (ClassNode n : stubs) { stubCache.put(n.name, n); } ClassNode stub = stubCache.get(type.getInternalName()); if (stub != null) { stubCache.put(type.getInternalName(), stub); ClassWriter cw = new ClassWriter(49); String[] ifaces = null; if (stub.interfaces != null) { int len = stub.interfaces.size(); ifaces = new String[len]; for (int i = 0; i < len; i++) { ifaces[i] = (String) stub.interfaces.get(i); } } cw.visit(stub.version, stub.access, stub.name, stub.signature, stub.superName, ifaces ); String outDirPath = cacheClassLoader.getPath(); if (outDirPath.indexOf(File.pathSeparator) != -1) { outDirPath = outDirPath.split(Pattern.quote(File.pathSeparator))[0]; } File outCache = new File(outDirPath, classFile); outCache.getParentFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream(outCache)) { fos.write(cw.toByteArray()); } catch (Exception ex) { throw new RuntimeException(ex); } return stub; } } } catch (IOException ex) { Logger.getLogger(JavaSourceClassLoader.class.getName()).log(Level.SEVERE, null, ex); } } int lastSlash = javaFile.lastIndexOf("/"); if (lastSlash == -1) { break; } javaFile = javaFile.substring(0, lastSlash) + ".java"; } return super.findStub(type); }
From source file:ca.weblite.asm.JavaSourceClassLoader.java
@Override public ClassNode findClass(Type type) { String classFile = type.getInternalName() + ".class"; ClassNode cached = cacheClassLoader.findClass(type); long cacheMtime = cacheClassLoader.getLastModified(); String javaFile = type.getInternalName() + ".java"; while (true) { File file = loader.getResource(javaFile); if (file != null) { try (FileInputStream bytecode = new FileInputStream(file)) { if (cached != null && cacheMtime >= lastModified) { // The cached version is up to date // no need to load the class return cached; }/*from w w w. ja v a2 s. c om*/ ClassNode node = new ClassNode(); ClassReader reader = new ClassReader(bytecode); reader.accept(node, ClassReader.SKIP_CODE); if ((node.name + ".java").equals(javaFile)) { return node; } } catch (IOException ex) { Logger.getLogger(JavaSourceClassLoader.class.getName()).log(Level.SEVERE, null, ex); } } int lastSlash = javaFile.lastIndexOf("/"); if (lastSlash == -1) { break; } javaFile = javaFile.substring(0, lastSlash) + ".java"; } return super.findClass(type); }
From source file:ca.weblite.asm.MirahClassIndex.java
public SourceFile findSourceFile(Type type) { try {/* www . ja v a 2 s . c o m*/ load(false); } catch (IOException ex) { Logger.getLogger(MirahClassIndex.class.getName()).log(Level.SEVERE, null, ex); } SourceFile out = index.get(type.getInternalName()); if (out == null && !updated) { try { updateIndex(); } catch (IOException ex) { Logger.getLogger(MirahClassIndex.class.getName()).log(Level.SEVERE, null, ex); } updated = true; return findSourceFile(type); } return out; }