diff options
248 files changed, 3951 insertions, 2497 deletions
@@ -11,6 +11,9 @@ <name>Javassist</name> <url>http://www.javassist.org/</url> + <properties> + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> + </properties> <organization> <name>Shigeru Chiba, www.javassist.org</name> </organization> @@ -167,7 +170,7 @@ <additionalClasspathElement>resources</additionalClasspathElement> </additionalClasspathElements> <forkMode>once</forkMode> - <workingDirectory>runtest</workingDirectory> + <workingDirectory>${project.build.directory}/runtest</workingDirectory> </configuration> </plugin> <plugin> @@ -207,6 +210,7 @@ <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> + <version>3.3.0</version> <executions> <execution> <id>bundle-manifest</id> @@ -308,10 +312,16 @@ </profiles> <dependencies> <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <version>3.8.1</version> - <scope>test</scope> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.hamcrest</groupId> + <artifactId>hamcrest-all</artifactId> + <version>1.3</version> + <scope>test</scope> </dependency> </dependencies> </project> diff --git a/src/main/javassist/ByteArrayClassPath.java b/src/main/javassist/ByteArrayClassPath.java index 00397470..b93bc892 100644 --- a/src/main/javassist/ByteArrayClassPath.java +++ b/src/main/javassist/ByteArrayClassPath.java @@ -16,9 +16,10 @@ package javassist; -import java.io.*; -import java.net.URL; +import java.io.ByteArrayInputStream; +import java.io.InputStream; import java.net.MalformedURLException; +import java.net.URL; /** * A <code>ByteArrayClassPath</code> contains bytes that is served as @@ -37,7 +38,7 @@ import java.net.MalformedURLException; * * <p>The <code>ClassPool</code> object <code>cp</code> uses the created * <code>ByteArrayClassPath</code> object as the source of the class file. - * + * * <p>A <code>ByteArrayClassPath</code> must be instantiated for every * class. It contains only a single class file. * @@ -62,6 +63,7 @@ public class ByteArrayClassPath implements ClassPath { this.classfile = classfile; } + @Override public String toString() { return "byte[]:" + classname; } @@ -69,16 +71,17 @@ public class ByteArrayClassPath implements ClassPath { /** * Opens the class file. */ + @Override public InputStream openClassfile(String classname) { if(this.classname.equals(classname)) return new ByteArrayInputStream(classfile); - else - return null; + return null; } /** * Obtains the URL. */ + @Override public URL find(String classname) { if(this.classname.equals(classname)) { String cname = classname.replace('.', '/') + ".class"; diff --git a/src/main/javassist/CannotCompileException.java b/src/main/javassist/CannotCompileException.java index 9c699287..d8a6e192 100644 --- a/src/main/javassist/CannotCompileException.java +++ b/src/main/javassist/CannotCompileException.java @@ -22,13 +22,16 @@ import javassist.compiler.CompileError; * Thrown when bytecode transformation has failed. */ public class CannotCompileException extends Exception { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private Throwable myCause; /** * Gets the cause of this throwable. * It is for JDK 1.3 compatibility. */ - public Throwable getCause() { + @Override + public synchronized Throwable getCause() { return (myCause == this ? null : myCause); } @@ -36,6 +39,7 @@ public class CannotCompileException extends Exception { * Initializes the cause of this throwable. * It is for JDK 1.3 compatibility. */ + @Override public synchronized Throwable initCause(Throwable cause) { myCause = cause; return this; @@ -49,8 +53,7 @@ public class CannotCompileException extends Exception { public String getReason() { if (message != null) return message; - else - return this.toString(); + return this.toString(); } /** diff --git a/src/main/javassist/ClassClassPath.java b/src/main/javassist/ClassClassPath.java index e1c44f08..0c2201fa 100644 --- a/src/main/javassist/ClassClassPath.java +++ b/src/main/javassist/ClassClassPath.java @@ -19,8 +19,6 @@ package javassist; import java.io.InputStream; import java.net.URL; -import javassist.bytecode.ClassFile; - /** * A search-path for obtaining a class file * by <code>getResourceAsStream()</code> in <code>java.lang.Class</code>. @@ -43,13 +41,13 @@ import javassist.bytecode.ClassFile; * <p>Class files in a named module are private to that module. * This method cannot obtain class files in named modules. * </p> - * + * * @see ClassPool#insertClassPath(ClassPath) * @see ClassPool#appendClassPath(ClassPath) * @see LoaderClassPath */ public class ClassClassPath implements ClassPath { - private Class thisClass; + private Class<?> thisClass; /** Creates a search path. * @@ -57,7 +55,7 @@ public class ClassClassPath implements ClassPath { * file. <code>getResourceAsStream()</code> is called on * this object. */ - public ClassClassPath(Class c) { + public ClassClassPath(Class<?> c) { thisClass = c; } @@ -76,6 +74,7 @@ public class ClassClassPath implements ClassPath { /** * Obtains a class file by <code>getResourceAsStream()</code>. */ + @Override public InputStream openClassfile(String classname) throws NotFoundException { String filename = '/' + classname.replace('.', '/') + ".class"; return thisClass.getResourceAsStream(filename); @@ -84,13 +83,15 @@ public class ClassClassPath implements ClassPath { /** * Obtains the URL of the specified class file. * - * @return null if the class file could not be found. + * @return null if the class file could not be found. */ + @Override public URL find(String classname) { String filename = '/' + classname.replace('.', '/') + ".class"; return thisClass.getResource(filename); } + @Override public String toString() { return thisClass.getName() + ".class"; } diff --git a/src/main/javassist/ClassMap.java b/src/main/javassist/ClassMap.java index a0bb9499..0e23e5f0 100644 --- a/src/main/javassist/ClassMap.java +++ b/src/main/javassist/ClassMap.java @@ -16,6 +16,8 @@ package javassist; +import java.util.HashMap; + import javassist.bytecode.Descriptor; /** @@ -47,7 +49,9 @@ import javassist.bytecode.Descriptor; * @see CtClass#replaceClassName(ClassMap) * @see CtNewMethod#copy(CtMethod,String,CtClass,ClassMap) */ -public class ClassMap extends java.util.HashMap { +public class ClassMap extends HashMap<String,String> { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private ClassMap parent; /** @@ -74,7 +78,7 @@ public class ClassMap extends java.util.HashMap { /** * Maps a class name to another name in this hashtable. * If the hashtable contains another mapping from the same - * class name, the old mapping is replaced. + * class name, the old mapping is replaced. * This method translates the given class names into the * internal form used in the JVM before putting it in * the hashtable. @@ -89,21 +93,23 @@ public class ClassMap extends java.util.HashMap { * @param newname the substituted class name. * @see #fix(String) */ - public void put(String oldname, String newname) { + @Override + public String put(String oldname, String newname) { if (oldname == newname) - return; + return oldname; String oldname2 = toJvmName(oldname); - String s = (String)get(oldname2); + String s = get(oldname2); if (s == null || !s.equals(oldname2)) - super.put(oldname2, toJvmName(newname)); + return super.put(oldname2, toJvmName(newname)); + return s; } /** * Is equivalent to <code>put()</code> except that * the given mapping is not recorded into the hashtable * if another mapping from <code>oldname</code> is - * already included. + * already included. * * @param oldname the original class name. * @param newname the substituted class name. @@ -113,13 +119,13 @@ public class ClassMap extends java.util.HashMap { return; String oldname2 = toJvmName(oldname); - String s = (String)get(oldname2); + String s = get(oldname2); if (s == null) super.put(oldname2, toJvmName(newname)); } - protected final void put0(Object oldname, Object newname) { - super.put(oldname, newname); + protected final String put0(String oldname, String newname) { + return super.put(oldname, newname); } /** @@ -132,14 +138,13 @@ public class ClassMap extends java.util.HashMap { * @see #toJvmName(String) * @see #toJavaName(String) */ - public Object get(Object jvmClassName) { - Object found = super.get(jvmClassName); + @Override + public String get(Object jvmClassName) { + String found = super.get(jvmClassName); if (found == null && parent != null) return parent.get(jvmClassName); - else - return found; + return found; } - /** * Prevents a mapping from the specified class name to another name. */ diff --git a/src/main/javassist/ClassPath.java b/src/main/javassist/ClassPath.java index 60fe80e9..5f10edc4 100644 --- a/src/main/javassist/ClassPath.java +++ b/src/main/javassist/ClassPath.java @@ -39,7 +39,7 @@ public interface ClassPath { * * <p>This method can return null if the specified class file is not * found. If null is returned, the next search path is examined. - * However, if an error happens, this method must throw an exception + * However, if an error happens, this method must throw an exception * so that the search will be terminated. * * <p>This method should not modify the contents of the class file. diff --git a/src/main/javassist/ClassPoolTail.java b/src/main/javassist/ClassPoolTail.java index 8e03873c..ebbfff99 100644 --- a/src/main/javassist/ClassPoolTail.java +++ b/src/main/javassist/ClassPoolTail.java @@ -48,6 +48,7 @@ final class DirClassPath implements ClassPath { directory = dirName; } + @Override public InputStream openClassfile(String classname) { try { char sep = File.separatorChar; @@ -60,6 +61,7 @@ final class DirClassPath implements ClassPath { return null; } + @Override public URL find(String classname) { char sep = File.separatorChar; String filename = directory + sep @@ -75,6 +77,7 @@ final class DirClassPath implements ClassPath { return null; } + @Override public String toString() { return directory; } @@ -85,6 +88,7 @@ final class JarDirClassPath implements ClassPath { JarDirClassPath(String dirName) throws NotFoundException { File[] files = new File(dirName).listFiles(new FilenameFilter() { + @Override public boolean accept(File dir, String name) { name = name.toLowerCase(); return name.endsWith(".jar") || name.endsWith(".zip"); @@ -98,6 +102,7 @@ final class JarDirClassPath implements ClassPath { } } + @Override public InputStream openClassfile(String classname) throws NotFoundException { if (jars != null) for (int i = 0; i < jars.length; i++) { @@ -109,6 +114,7 @@ final class JarDirClassPath implements ClassPath { return null; // not found } + @Override public URL find(String classname) { if (jars != null) for (int i = 0; i < jars.length; i++) { @@ -174,6 +180,7 @@ final class JarClassPath implements ClassPath { } @Override + @Override public String toString() { return jarfileURL == null ? "<null>" : jarfileURL.toString(); } @@ -186,6 +193,7 @@ final class ClassPoolTail { pathList = null; } + @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("[class path: "); @@ -237,10 +245,8 @@ final class ClassPoolTail { public ClassPath appendSystemPath() { if (javassist.bytecode.ClassFile.MAJOR_VERSION < javassist.bytecode.ClassFile.JAVA_9) return appendClassPath(new ClassClassPath()); - else { - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - return appendClassPath(new LoaderClassPath(cl)); - } + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + return appendClassPath(new LoaderClassPath(cl)); } public ClassPath insertClassPath(String pathname) @@ -341,8 +347,7 @@ final class ClassPoolTail { if (error != null) throw error; - else - return null; // not found + return null; // not found } /** diff --git a/src/main/javassist/CodeConverter.java b/src/main/javassist/CodeConverter.java index bbc5c77d..6df3622c 100644 --- a/src/main/javassist/CodeConverter.java +++ b/src/main/javassist/CodeConverter.java @@ -16,8 +16,21 @@ package javassist; -import javassist.bytecode.*; -import javassist.convert.*; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.MethodInfo; +import javassist.convert.TransformAccessArrayField; +import javassist.convert.TransformAfter; +import javassist.convert.TransformBefore; +import javassist.convert.TransformCall; +import javassist.convert.TransformFieldAccess; +import javassist.convert.TransformNew; +import javassist.convert.TransformNewClass; +import javassist.convert.TransformReadField; +import javassist.convert.TransformWriteField; +import javassist.convert.Transformer; /** * Simple translator of method bodies @@ -666,6 +679,7 @@ public class CodeConverter { * Returns "arrayReadByteOrBoolean" as the name of the static method with the signature * (Ljava/lang/Object;I)B to replace reading from a byte[]. */ + @Override public String byteOrBooleanRead() { return "arrayReadByteOrBoolean"; @@ -675,6 +689,7 @@ public class CodeConverter { * Returns "arrayWriteByteOrBoolean" as the name of the static method with the signature * (Ljava/lang/Object;IB)V to replace writing to a byte[]. */ + @Override public String byteOrBooleanWrite() { return "arrayWriteByteOrBoolean"; @@ -684,6 +699,7 @@ public class CodeConverter { * Returns "arrayReadChar" as the name of the static method with the signature * (Ljava/lang/Object;I)C to replace reading from a char[]. */ + @Override public String charRead() { return "arrayReadChar"; @@ -693,6 +709,7 @@ public class CodeConverter { * Returns "arrayWriteChar" as the name of the static method with the signature * (Ljava/lang/Object;IC)V to replace writing to a byte[]. */ + @Override public String charWrite() { return "arrayWriteChar"; @@ -702,6 +719,7 @@ public class CodeConverter { * Returns "arrayReadDouble" as the name of the static method with the signature * (Ljava/lang/Object;I)D to replace reading from a double[]. */ + @Override public String doubleRead() { return "arrayReadDouble"; @@ -711,6 +729,7 @@ public class CodeConverter { * Returns "arrayWriteDouble" as the name of the static method with the signature * (Ljava/lang/Object;ID)V to replace writing to a double[]. */ + @Override public String doubleWrite() { return "arrayWriteDouble"; @@ -720,6 +739,7 @@ public class CodeConverter { * Returns "arrayReadFloat" as the name of the static method with the signature * (Ljava/lang/Object;I)F to replace reading from a float[]. */ + @Override public String floatRead() { return "arrayReadFloat"; @@ -729,6 +749,7 @@ public class CodeConverter { * Returns "arrayWriteFloat" as the name of the static method with the signature * (Ljava/lang/Object;IF)V to replace writing to a float[]. */ + @Override public String floatWrite() { return "arrayWriteFloat"; @@ -738,6 +759,7 @@ public class CodeConverter { * Returns "arrayReadInt" as the name of the static method with the signature * (Ljava/lang/Object;I)I to replace reading from a int[]. */ + @Override public String intRead() { return "arrayReadInt"; @@ -747,6 +769,7 @@ public class CodeConverter { * Returns "arrayWriteInt" as the name of the static method with the signature * (Ljava/lang/Object;II)V to replace writing to a int[]. */ + @Override public String intWrite() { return "arrayWriteInt"; @@ -756,6 +779,7 @@ public class CodeConverter { * Returns "arrayReadLong" as the name of the static method with the signature * (Ljava/lang/Object;I)J to replace reading from a long[]. */ + @Override public String longRead() { return "arrayReadLong"; @@ -765,6 +789,7 @@ public class CodeConverter { * Returns "arrayWriteLong" as the name of the static method with the signature * (Ljava/lang/Object;IJ)V to replace writing to a long[]. */ + @Override public String longWrite() { return "arrayWriteLong"; @@ -774,6 +799,7 @@ public class CodeConverter { * Returns "arrayReadObject" as the name of the static method with the signature * (Ljava/lang/Object;I)Ljava/lang/Object; to replace reading from a Object[] (or any subclass of object). */ + @Override public String objectRead() { return "arrayReadObject"; @@ -783,6 +809,7 @@ public class CodeConverter { * Returns "arrayWriteObject" as the name of the static method with the signature * (Ljava/lang/Object;ILjava/lang/Object;)V to replace writing to a Object[] (or any subclass of object). */ + @Override public String objectWrite() { return "arrayWriteObject"; @@ -792,6 +819,7 @@ public class CodeConverter { * Returns "arrayReadShort" as the name of the static method with the signature * (Ljava/lang/Object;I)S to replace reading from a short[]. */ + @Override public String shortRead() { return "arrayReadShort"; @@ -801,6 +829,7 @@ public class CodeConverter { * Returns "arrayWriteShort" as the name of the static method with the signature * (Ljava/lang/Object;IS)V to replace writing to a short[]. */ + @Override public String shortWrite() { return "arrayWriteShort"; diff --git a/src/main/javassist/CtArray.java b/src/main/javassist/CtArray.java index 6bbbf490..1b30cb70 100644 --- a/src/main/javassist/CtArray.java +++ b/src/main/javassist/CtArray.java @@ -19,26 +19,34 @@ package javassist; /** * Array types. */ -final class CtArray extends CtClass { +final class CtArray extends CtClass +{ protected ClassPool pool; // the name of array type ends with "[]". - CtArray(String name, ClassPool cp) { + CtArray(String name, ClassPool cp) + { super(name); pool = cp; } - public ClassPool getClassPool() { + @Override + public ClassPool getClassPool() + { return pool; } - public boolean isArray() { + @Override + public boolean isArray() + { return true; } private CtClass[] interfaces = null; - public int getModifiers() { + @Override + public int getModifiers() + { int mod = Modifier.FINAL; try { mod |= getComponentType().getModifiers() @@ -48,9 +56,11 @@ final class CtArray extends CtClass { return mod; } - public CtClass[] getInterfaces() throws NotFoundException { + @Override + public CtClass[] getInterfaces() throws NotFoundException + { if (interfaces == null) { - Class[] intfs = Object[].class.getInterfaces(); + Class<?>[] intfs = Object[].class.getInterfaces(); // java.lang.Cloneable and java.io.Serializable. // If the JVM is CLDC, intfs is empty. interfaces = new CtClass[intfs.length]; @@ -61,7 +71,9 @@ final class CtArray extends CtClass { return interfaces; } - public boolean subtypeOf(CtClass clazz) throws NotFoundException { + @Override + public boolean subtypeOf(CtClass clazz) throws NotFoundException + { if (super.subtypeOf(clazz)) return true; @@ -78,16 +90,22 @@ final class CtArray extends CtClass { && getComponentType().subtypeOf(clazz.getComponentType()); } - public CtClass getComponentType() throws NotFoundException { + @Override + public CtClass getComponentType() throws NotFoundException + { String name = getName(); return pool.get(name.substring(0, name.length() - 2)); } - public CtClass getSuperclass() throws NotFoundException { + @Override + public CtClass getSuperclass() throws NotFoundException + { return pool.get(javaLangObject); } - public CtMethod[] getMethods() { + @Override + public CtMethod[] getMethods() + { try { return getSuperclass().getMethods(); } @@ -96,13 +114,16 @@ final class CtArray extends CtClass { } } + @Override public CtMethod getMethod(String name, String desc) throws NotFoundException { return getSuperclass().getMethod(name, desc); } - public CtConstructor[] getConstructors() { + @Override + public CtConstructor[] getConstructors() + { try { return getSuperclass().getConstructors(); } diff --git a/src/main/javassist/CtBehavior.java b/src/main/javassist/CtBehavior.java index 75af53b8..1b9dbf0b 100644 --- a/src/main/javassist/CtBehavior.java +++ b/src/main/javassist/CtBehavior.java @@ -16,9 +16,27 @@ package javassist; -import javassist.bytecode.*; -import javassist.compiler.Javac; +import javassist.bytecode.AccessFlag; +import javassist.bytecode.AnnotationsAttribute; +import javassist.bytecode.AttributeInfo; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.ExceptionsAttribute; +import javassist.bytecode.LineNumberAttribute; +import javassist.bytecode.LocalVariableAttribute; +import javassist.bytecode.LocalVariableTypeAttribute; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; +import javassist.bytecode.ParameterAnnotationsAttribute; +import javassist.bytecode.SignatureAttribute; +import javassist.bytecode.StackMap; +import javassist.bytecode.StackMapTable; import javassist.compiler.CompileError; +import javassist.compiler.Javac; import javassist.expr.ExprEditor; /** @@ -81,6 +99,7 @@ public abstract class CtBehavior extends CtMember { } } + @Override protected void extendToString(StringBuffer buffer) { buffer.append(' '); buffer.append(getName()); @@ -140,6 +159,7 @@ public abstract class CtBehavior extends CtMember { * <code>javassist.Modifier</code>. * @see Modifier */ + @Override public int getModifiers() { return AccessFlag.toModifier(methodInfo.getAccessFlags()); } @@ -153,6 +173,7 @@ public abstract class CtBehavior extends CtMember { * * @see Modifier */ + @Override public void setModifiers(int mod) { declaringClass.checkModify(); methodInfo.setAccessFlags(AccessFlag.of(mod)); @@ -166,6 +187,7 @@ public abstract class CtBehavior extends CtMember { * otherwise <code>false</code>. * @since 3.21 */ + @Override public boolean hasAnnotation(String typeName) { MethodInfo mi = getMethodInfo2(); AnnotationsAttribute ainfo = (AnnotationsAttribute) @@ -188,7 +210,8 @@ public abstract class CtBehavior extends CtMember { * @return the annotation if found, otherwise <code>null</code>. * @since 3.11 */ - public Object getAnnotation(Class clz) throws ClassNotFoundException { + @Override + public Object getAnnotation(Class<?> clz) throws ClassNotFoundException { MethodInfo mi = getMethodInfo2(); AnnotationsAttribute ainfo = (AnnotationsAttribute) mi.getAttribute(AnnotationsAttribute.invisibleTag); @@ -206,6 +229,7 @@ public abstract class CtBehavior extends CtMember { * @see #getAvailableAnnotations() * @since 3.1 */ + @Override public Object[] getAnnotations() throws ClassNotFoundException { return getAnnotations(false); } @@ -219,6 +243,7 @@ public abstract class CtBehavior extends CtMember { * @see #getAnnotations() * @since 3.3 */ + @Override public Object[] getAvailableAnnotations(){ try{ return getAnnotations(true); @@ -324,6 +349,7 @@ public abstract class CtBehavior extends CtMember { * @see javassist.bytecode.Descriptor * @see #getGenericSignature() */ + @Override public String getSignature() { return methodInfo.getDescriptor(); } @@ -335,6 +361,7 @@ public abstract class CtBehavior extends CtMember { * @see SignatureAttribute#toMethodSignature(String) * @since 3.17 */ + @Override public String getGenericSignature() { SignatureAttribute sa = (SignatureAttribute)methodInfo.getAttribute(SignatureAttribute.tag); @@ -351,6 +378,7 @@ public abstract class CtBehavior extends CtMember { * @see javassist.bytecode.SignatureAttribute.MethodSignature#encode() * @since 3.17 */ + @Override public void setGenericSignature(String sig) { declaringClass.checkModify(); methodInfo.addAttribute(new SignatureAttribute(methodInfo.getConstPool(), sig)); @@ -489,12 +517,13 @@ public abstract class CtBehavior extends CtMember { * * @param name attribute name */ - public byte[] getAttribute(String name) { + @Override + public byte[] getAttribute(String name) + { AttributeInfo ai = methodInfo.getAttribute(name); if (ai == null) return null; - else - return ai.get(); + return ai.get(); } /** @@ -507,7 +536,9 @@ public abstract class CtBehavior extends CtMember { * @param name attribute name * @param data attribute value */ - public void setAttribute(String name, byte[] data) { + @Override + public void setAttribute(String name, byte[] data) + { declaringClass.checkModify(); methodInfo.addAttribute(new AttributeInfo(methodInfo.getConstPool(), name, data)); @@ -530,7 +561,8 @@ public abstract class CtBehavior extends CtMember { * * @see javassist.runtime.Cflow */ - public void useCflow(String name) throws CannotCompileException { + public void useCflow(String name) throws CannotCompileException + { CtClass cc = declaringClass; cc.checkModify(); ClassPool pool = cc.getClassPool(); diff --git a/src/main/javassist/CtClass.java b/src/main/javassist/CtClass.java index aacb59d8..190423cc 100644 --- a/src/main/javassist/CtClass.java +++ b/src/main/javassist/CtClass.java @@ -198,6 +198,7 @@ public abstract class CtClass { /** * Converts the object to a string. */ + @Override public String toString() { StringBuffer buf = new StringBuffer(getClass().getName()); buf.append("@"); @@ -361,8 +362,7 @@ public abstract class CtClass { int index = qname.lastIndexOf('.'); if (index < 0) return qname; - else - return qname.substring(index + 1); + return qname.substring(index + 1); } /** @@ -373,8 +373,7 @@ public abstract class CtClass { int index = qname.lastIndexOf('.'); if (index < 0) return null; - else - return qname.substring(0, index); + return qname.substring(0, index); } /** @@ -517,27 +516,30 @@ public abstract class CtClass { * * @return a <code>Collection<String></code> object. */ - public synchronized Collection getRefClasses() { + public synchronized Collection<String> getRefClasses() { ClassFile cf = getClassFile2(); if (cf != null) { ClassMap cm = new ClassMap() { - public void put(String oldname, String newname) { - put0(oldname, newname); + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + @Override + public String put(String oldname, String newname) { + return put0(oldname, newname); } - - public Object get(Object jvmClassName) { + @Override + public String get(Object jvmClassName) { String n = toJavaName((String)jvmClassName); put0(n, n); return null; } + @Override public void fix(String name) {} }; cf.getRefClasses(cm); return cm.values(); } - else - return null; + return null; } /** @@ -588,7 +590,7 @@ public abstract class CtClass { * @return <code>true</code> if the annotation is found, otherwise <code>false</code>. * @since 3.11 */ - public boolean hasAnnotation(Class annotationType) { + public boolean hasAnnotation(Class<?> annotationType) { return hasAnnotation(annotationType.getName()); } @@ -614,7 +616,7 @@ public abstract class CtClass { * @return the annotation if found, otherwise <code>null</code>. * @since 3.11 */ - public Object getAnnotation(Class clz) throws ClassNotFoundException { + public Object getAnnotation(Class<?> clz) throws ClassNotFoundException { return null; } @@ -782,6 +784,7 @@ public abstract class CtClass { * Use {@link #getEnclosingBehavior()}. * @see #getEnclosingBehavior() */ + @Deprecated public final CtMethod getEnclosingMethod() throws NotFoundException { CtBehavior b = getEnclosingBehavior(); if (b == null) @@ -1271,7 +1274,7 @@ public abstract class CtClass { * @see #toClass(java.lang.ClassLoader,ProtectionDomain) * @see ClassPool#toClass(CtClass) */ - public Class toClass() throws CannotCompileException { + public Class<?> toClass() throws CannotCompileException { return getClassPool().toClass(this); } @@ -1306,7 +1309,7 @@ public abstract class CtClass { * @see ClassPool#toClass(CtClass,java.lang.ClassLoader) * @since 3.3 */ - public Class toClass(ClassLoader loader, ProtectionDomain domain) + public Class<?> toClass(ClassLoader loader, ProtectionDomain domain) throws CannotCompileException { ClassPool cp = getClassPool(); @@ -1325,7 +1328,8 @@ public abstract class CtClass { * * @deprecated Replaced by {@link #toClass(ClassLoader,ProtectionDomain)} */ - public final Class toClass(ClassLoader loader) + @Deprecated + public final Class<?> toClass(ClassLoader loader) throws CannotCompileException { return getClassPool().toClass(this, loader); @@ -1544,27 +1548,32 @@ public abstract class CtClass { file = new FileOutputStream(filename); } + @Override public void write(int b) throws IOException { init(); file.write(b); } + @Override public void write(byte[] b) throws IOException { init(); file.write(b); } + @Override public void write(byte[] b, int off, int len) throws IOException { init(); file.write(b, off, len); } + @Override public void flush() throws IOException { init(); file.flush(); } + @Override public void close() throws IOException { init(); file.close(); diff --git a/src/main/javassist/CtClassType.java b/src/main/javassist/CtClassType.java index b0a8819d..0c2f775e 100644 --- a/src/main/javassist/CtClassType.java +++ b/src/main/javassist/CtClassType.java @@ -16,31 +16,33 @@ package javassist; -import java.lang.ref.WeakReference; import java.io.BufferedInputStream; -import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.List; +import java.util.Map; import java.util.Set; import javassist.bytecode.AccessFlag; -import javassist.bytecode.AttributeInfo; import javassist.bytecode.AnnotationsAttribute; +import javassist.bytecode.AttributeInfo; import javassist.bytecode.BadBytecode; import javassist.bytecode.Bytecode; import javassist.bytecode.ClassFile; import javassist.bytecode.CodeAttribute; -import javassist.bytecode.ConstantAttribute; import javassist.bytecode.CodeIterator; import javassist.bytecode.ConstPool; +import javassist.bytecode.ConstantAttribute; import javassist.bytecode.Descriptor; import javassist.bytecode.EnclosingMethodAttribute; import javassist.bytecode.FieldInfo; @@ -55,7 +57,7 @@ import javassist.compiler.Javac; import javassist.expr.ExprEditor; /** - * Class types. + * Class<?> types. */ class CtClassType extends CtClass { ClassPool classPool; @@ -66,11 +68,11 @@ class CtClassType extends CtClass { ClassFile classfile; byte[] rawClassfile; // backup storage - private WeakReference memberCache; + private Reference<CtMember.Cache> memberCache; private AccessorMaker accessors; private FieldInitLink fieldInitializers; - private Hashtable hiddenMethods; // must be synchronous + private Map<CtMethod,String> hiddenMethods; // must be synchronous private int uniqueNumberSeed; private boolean doPruning = ClassPool.doPruning; @@ -103,6 +105,7 @@ class CtClassType extends CtClass { qualifiedName = classfile.getName(); } + @Override protected void extendToString(StringBuffer buffer) { if (wasChanged) buffer.append("changed "); @@ -162,6 +165,7 @@ class CtClassType extends CtClass { } } + @Override public AccessorMaker getAccessorMaker() { if (accessors == null) accessors = new AccessorMaker(this); @@ -169,6 +173,7 @@ class CtClassType extends CtClass { return accessors; } + @Override public ClassFile getClassFile2() { return getClassFile3(true); } @@ -229,6 +234,7 @@ class CtClassType extends CtClass { * @see javassist.CtClass#incGetCounter() * @see #toBytecode(DataOutputStream) */ + @Override final void incGetCounter() { ++getCount; } /** @@ -236,6 +242,7 @@ class CtClassType extends CtClass { * It releases the class files that have not been recently used * if they are unmodified. */ + @Override void compress() { if (getCount < GET_THRESHOLD) if (!isModified() && ClassPool.releaseUnmodifiedClassFile) @@ -282,24 +289,29 @@ class CtClassType extends CtClass { return classfile; } + @Override public ClassPool getClassPool() { return classPool; } void setClassPool(ClassPool cp) { classPool = cp; } + @Override public URL getURL() throws NotFoundException { URL url = classPool.find(getName()); if (url == null) throw new NotFoundException(getName()); - else - return url; + return url; } + @Override public boolean isModified() { return wasChanged; } + @Override public boolean isFrozen() { return wasFrozen; } + @Override public void freeze() { wasFrozen = true; } + @Override void checkModify() throws RuntimeException { if (isFrozen()) { String msg = getName() + " class is frozen"; @@ -312,11 +324,13 @@ class CtClassType extends CtClass { wasChanged = true; } + @Override public void defrost() { checkPruned("defrost"); wasFrozen = false; } + @Override public boolean subtypeOf(CtClass clazz) throws NotFoundException { int i; String cname = clazz.getName(); @@ -344,6 +358,7 @@ class CtClassType extends CtClass { return false; } + @Override public void setName(String name) throws RuntimeException { String oldname = getName(); if (name.equals(oldname)) @@ -358,24 +373,27 @@ class CtClassType extends CtClass { classPool.classNameChanged(oldname, this); } + @Override public String getGenericSignature() { SignatureAttribute sa = (SignatureAttribute)getClassFile2().getAttribute(SignatureAttribute.tag); return sa == null ? null : sa.getSignature(); } + @Override public void setGenericSignature(String sig) { ClassFile cf = getClassFile(); SignatureAttribute sa = new SignatureAttribute(cf.getConstPool(), sig); cf.addAttribute(sa); } + @Override public void replaceClassName(ClassMap classnames) throws RuntimeException { String oldClassName = getName(); String newClassName - = (String)classnames.get(Descriptor.toJvmName(oldClassName)); + = classnames.get(Descriptor.toJvmName(oldClassName)); if (newClassName != null) { newClassName = Descriptor.toJavaName(newClassName); // check this in advance although classNameChanged() below does. @@ -393,6 +411,7 @@ class CtClassType extends CtClass { } } + @Override public void replaceClassName(String oldname, String newname) throws RuntimeException { @@ -406,18 +425,22 @@ class CtClassType extends CtClass { } } + @Override public boolean isInterface() { return Modifier.isInterface(getModifiers()); } + @Override public boolean isAnnotation() { return Modifier.isAnnotation(getModifiers()); } + @Override public boolean isEnum() { return Modifier.isEnum(getModifiers()); } + @Override public int getModifiers() { ClassFile cf = getClassFile2(); int acc = cf.getAccessFlags(); @@ -429,6 +452,7 @@ class CtClassType extends CtClass { return AccessFlag.toModifier(acc); } + @Override public CtClass[] getNestedClasses() throws NotFoundException { ClassFile cf = getClassFile2(); InnerClassesAttribute ica @@ -438,7 +462,7 @@ class CtClassType extends CtClass { String thisName = cf.getName() + "$"; int n = ica.tableLength(); - ArrayList list = new ArrayList(n); + List<CtClass> list = new ArrayList<CtClass>(n); for (int i = 0; i < n; i++) { String name = ica.innerClass(i); if (name != null) @@ -449,9 +473,10 @@ class CtClassType extends CtClass { } } - return (CtClass[])list.toArray(new CtClass[list.size()]); + return list.toArray(new CtClass[list.size()]); } + @Override public void setModifiers(int mod) { checkModify(); updateInnerEntry(mod, getName(), this, true); @@ -495,7 +520,7 @@ class CtClassType extends CtClass { + " into a static class"); } - //@Override + @Override public boolean hasAnnotation(String annotationName) { ClassFile cf = getClassFile2(); AnnotationsAttribute ainfo = (AnnotationsAttribute) @@ -508,7 +533,8 @@ class CtClassType extends CtClass { /** * @deprecated */ - static boolean hasAnnotationType(Class clz, ClassPool cp, + @Deprecated + static boolean hasAnnotationType(Class<?> clz, ClassPool cp, AnnotationsAttribute a1, AnnotationsAttribute a2) { @@ -544,7 +570,8 @@ class CtClassType extends CtClass { return false; } - public Object getAnnotation(Class clz) throws ClassNotFoundException { + @Override + public Object getAnnotation(Class<?> clz) throws ClassNotFoundException { ClassFile cf = getClassFile2(); AnnotationsAttribute ainfo = (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.invisibleTag); @@ -553,7 +580,7 @@ class CtClassType extends CtClass { return getAnnotationType(clz, getClassPool(), ainfo, ainfo2); } - static Object getAnnotationType(Class clz, ClassPool cp, + static Object getAnnotationType(Class<?> clz, ClassPool cp, AnnotationsAttribute a1, AnnotationsAttribute a2) throws ClassNotFoundException { @@ -583,10 +610,12 @@ class CtClassType extends CtClass { return null; } + @Override public Object[] getAnnotations() throws ClassNotFoundException { return getAnnotations(false); } + @Override public Object[] getAvailableAnnotations(){ try { return getAnnotations(true); @@ -642,23 +671,19 @@ class CtClassType extends CtClass { return result; } - else{ - ArrayList annotations = new ArrayList(); - for (int i = 0 ; i < size1 ; i++){ - try{ - annotations.add(toAnnoType(anno1[i], cp)); - } - catch(ClassNotFoundException e){} - } - for (int j = 0; j < size2; j++) { - try{ - annotations.add(toAnnoType(anno2[j], cp)); - } - catch(ClassNotFoundException e){} - } + List<Object> annotations = new ArrayList<Object>(); + for (int i = 0 ; i < size1 ; i++) + try{ + annotations.add(toAnnoType(anno1[i], cp)); + } + catch(ClassNotFoundException e){} + for (int j = 0; j < size2; j++) + try{ + annotations.add(toAnnoType(anno2[j], cp)); + } + catch(ClassNotFoundException e){} - return annotations.toArray(); - } + return annotations.toArray(); } static Object[][] toAnnotationType(boolean ignoreNotFound, ClassPool cp, @@ -707,7 +732,7 @@ class CtClassType extends CtClass { result[i][j + size1] = toAnnoType(anno2[j], cp); } else{ - ArrayList annotations = new ArrayList(); + List<Object> annotations = new ArrayList<Object>(); for (int j = 0 ; j < size1 ; j++){ try{ annotations.add(toAnnoType(anno1[j], cp)); @@ -742,7 +767,7 @@ class CtClassType extends CtClass { } catch (ClassNotFoundException e2){ try { - Class clazz = cp.get(anno.getTypeName()).toClass(); + Class<?> clazz = cp.get(anno.getTypeName()).toClass(); return javassist.bytecode.annotation.AnnotationImpl.make( clazz.getClassLoader(), clazz, cp, anno); @@ -754,6 +779,7 @@ class CtClassType extends CtClass { } } + @Override public boolean subclassOf(CtClass superclass) { if (superclass == null) return false; @@ -772,14 +798,15 @@ class CtClassType extends CtClass { return false; } + @Override public CtClass getSuperclass() throws NotFoundException { String supername = getClassFile2().getSuperclass(); if (supername == null) return null; - else - return classPool.get(supername); + return classPool.get(supername); } + @Override public void setSuperclass(CtClass clazz) throws CannotCompileException { checkModify(); if (isInterface()) @@ -788,6 +815,7 @@ class CtClassType extends CtClass { getClassFile2().setSuperclass(clazz.getName()); } + @Override public CtClass[] getInterfaces() throws NotFoundException { String[] ifs = getClassFile2().getInterfaces(); int num = ifs.length; @@ -798,6 +826,7 @@ class CtClassType extends CtClass { return ifc; } + @Override public void setInterfaces(CtClass[] list) { checkModify(); String[] ifs; @@ -813,12 +842,14 @@ class CtClassType extends CtClass { getClassFile2().setInterfaces(ifs); } + @Override public void addInterface(CtClass anInterface) { checkModify(); if (anInterface != null) getClassFile2().addInterface(anInterface.getName()); } + @Override public CtClass getDeclaringClass() throws NotFoundException { ClassFile cf = getClassFile2(); InnerClassesAttribute ica = (InnerClassesAttribute)cf.getAttribute( @@ -833,39 +864,41 @@ class CtClassType extends CtClass { String outName = ica.outerClass(i); if (outName != null) return classPool.get(outName); - else { - // maybe anonymous or local class. - EnclosingMethodAttribute ema - = (EnclosingMethodAttribute)cf.getAttribute( - EnclosingMethodAttribute.tag); - if (ema != null) - return classPool.get(ema.className()); - } + + // maybe anonymous or local class. + EnclosingMethodAttribute ema + = (EnclosingMethodAttribute)cf.getAttribute( + EnclosingMethodAttribute.tag); + if (ema != null) + return classPool.get(ema.className()); + } return null; } - public CtBehavior getEnclosingBehavior() throws NotFoundException { + @Override + public CtBehavior getEnclosingBehavior() throws NotFoundException + { ClassFile cf = getClassFile2(); EnclosingMethodAttribute ema = (EnclosingMethodAttribute)cf.getAttribute( EnclosingMethodAttribute.tag); if (ema == null) return null; - else { - CtClass enc = classPool.get(ema.className()); - String name = ema.methodName(); - if (MethodInfo.nameInit.equals(name)) - return enc.getConstructor(ema.methodDescriptor()); - else if(MethodInfo.nameClinit.equals(name)) - return enc.getClassInitializer(); - else - return enc.getMethod(name, ema.methodDescriptor()); - } + CtClass enc = classPool.get(ema.className()); + String name = ema.methodName(); + if (MethodInfo.nameInit.equals(name)) + return enc.getConstructor(ema.methodDescriptor()); + else if(MethodInfo.nameClinit.equals(name)) + return enc.getClassInitializer(); + else + return enc.getMethod(name, ema.methodDescriptor()); } - public CtClass makeNestedClass(String name, boolean isStatic) { + @Override + public CtClass makeNestedClass(String name, boolean isStatic) + { if (!isStatic) throw new RuntimeException( "sorry, only nested static class is supported"); @@ -905,60 +938,47 @@ class CtClassType extends CtClass { * Returns null if members are not cached. */ protected CtMember.Cache hasMemberCache() { - WeakReference cache = memberCache; - if (cache != null) - return (CtMember.Cache)cache.get(); - else - return null; + if (memberCache != null) + return memberCache.get(); + return null; } protected synchronized CtMember.Cache getMembers() { CtMember.Cache cache = null; if (memberCache == null - || (cache = (CtMember.Cache)memberCache.get()) == null) { + || (cache = memberCache.get()) == null) { cache = new CtMember.Cache(this); makeFieldCache(cache); makeBehaviorCache(cache); - memberCache = new WeakReference(cache); + memberCache = new WeakReference<CtMember.Cache>(cache); } return cache; } private void makeFieldCache(CtMember.Cache cache) { - List list = getClassFile3(false).getFields(); - int n = list.size(); - for (int i = 0; i < n; ++i) { - FieldInfo finfo = (FieldInfo)list.get(i); - CtField newField = new CtField(finfo, this); - cache.addField(newField); - } + List<FieldInfo> fields = getClassFile3(false).getFields(); + for (FieldInfo finfo:fields) + cache.addField(new CtField(finfo, this)); } private void makeBehaviorCache(CtMember.Cache cache) { - List list = getClassFile3(false).getMethods(); - int n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); - if (minfo.isMethod()) { - CtMethod newMethod = new CtMethod(minfo, this); - cache.addMethod(newMethod); - } - else { - CtConstructor newCons = new CtConstructor(minfo, this); - cache.addConstructor(newCons); - } - } + List<MethodInfo> methods = getClassFile3(false).getMethods(); + for (MethodInfo minfo:methods) + if (minfo.isMethod()) + cache.addMethod(new CtMethod(minfo, this)); + else + cache.addConstructor(new CtConstructor(minfo, this)); } + @Override public CtField[] getFields() { - ArrayList alist = new ArrayList(); + List<CtMember> alist = new ArrayList<CtMember>(); getFields(alist, this); - return (CtField[])alist.toArray(new CtField[alist.size()]); + return alist.toArray(new CtField[alist.size()]); } - private static void getFields(ArrayList alist, CtClass cc) { - int i, num; + private static void getFields(List<CtMember> alist, CtClass cc) { if (cc == null) return; @@ -969,9 +989,8 @@ class CtClassType extends CtClass { try { CtClass[] ifs = cc.getInterfaces(); - num = ifs.length; - for (i = 0; i < num; ++i) - getFields(alist, ifs[i]); + for (CtClass ctc : ifs) + getFields(alist, ctc); } catch (NotFoundException e) {} @@ -985,6 +1004,7 @@ class CtClassType extends CtClass { } } + @Override public CtField getField(String name, String desc) throws NotFoundException { CtField f = getField2(name, desc); return checkGetField(f, name, desc); @@ -1000,10 +1020,10 @@ class CtClassType extends CtClass { throw new NotFoundException(msg + " in " + getName()); } - else - return f; + return f; } + @Override CtField getField2(String name, String desc) { CtField df = getDeclaredField2(name, desc); if (df != null) @@ -1011,9 +1031,8 @@ class CtClassType extends CtClass { try { CtClass[] ifs = getInterfaces(); - int num = ifs.length; - for (int i = 0; i < num; ++i) { - CtField f = ifs[i].getField2(name, desc); + for (CtClass ctc : ifs) { + CtField f = ctc.getField2(name, desc); if (f != null) return f; } @@ -1026,6 +1045,7 @@ class CtClassType extends CtClass { return null; } + @Override public CtField[] getDeclaredFields() { CtMember.Cache memCache = getMembers(); CtMember field = memCache.fieldHead(); @@ -1041,10 +1061,12 @@ class CtClassType extends CtClass { return cfs; } + @Override public CtField getDeclaredField(String name) throws NotFoundException { return getDeclaredField(name, null); } + @Override public CtField getDeclaredField(String name, String desc) throws NotFoundException { CtField f = getDeclaredField2(name, desc); return checkGetField(f, name, desc); @@ -1064,6 +1086,7 @@ class CtClassType extends CtClass { return null; } + @Override public CtBehavior[] getDeclaredBehaviors() { CtMember.Cache memCache = getMembers(); CtMember cons = memCache.consHead(); @@ -1088,6 +1111,7 @@ class CtClassType extends CtClass { return cb; } + @Override public CtConstructor[] getConstructors() { CtMember.Cache memCache = getMembers(); CtMember cons = memCache.consHead(); @@ -1119,6 +1143,7 @@ class CtClassType extends CtClass { && cons.isConstructor(); } + @Override public CtConstructor getConstructor(String desc) throws NotFoundException { @@ -1137,6 +1162,7 @@ class CtClassType extends CtClass { return super.getConstructor(desc); } + @Override public CtConstructor[] getDeclaredConstructors() { CtMember.Cache memCache = getMembers(); CtMember cons = memCache.consHead(); @@ -1164,6 +1190,7 @@ class CtClassType extends CtClass { return result; } + @Override public CtConstructor getClassInitializer() { CtMember.Cache memCache = getMembers(); CtMember cons = memCache.consHead(); @@ -1179,18 +1206,18 @@ class CtClassType extends CtClass { return null; } + @Override public CtMethod[] getMethods() { - HashMap h = new HashMap(); + Map<String,CtMember> h = new HashMap<String,CtMember>(); getMethods0(h, this); - return (CtMethod[])h.values().toArray(new CtMethod[h.size()]); + return h.values().toArray(new CtMethod[h.size()]); } - private static void getMethods0(HashMap h, CtClass cc) { + private static void getMethods0(Map<String,CtMember> h, CtClass cc) { try { CtClass[] ifs = cc.getInterfaces(); - int size = ifs.length; - for (int i = 0; i < size; ++i) - getMethods0(h, ifs[i]); + for (CtClass ctc : ifs) + getMethods0(h, ctc); } catch (NotFoundException e) {} @@ -1214,15 +1241,15 @@ class CtClassType extends CtClass { } } + @Override public CtMethod getMethod(String name, String desc) throws NotFoundException { CtMethod m = getMethod0(this, name, desc); if (m != null) return m; - else - throw new NotFoundException(name + "(..) is not found in " - + getName()); + throw new NotFoundException(name + "(..) is not found in " + + getName()); } private static CtMethod getMethod0(CtClass cc, @@ -1252,9 +1279,8 @@ class CtClassType extends CtClass { try { CtClass[] ifs = cc.getInterfaces(); - int size = ifs.length; - for (int i = 0; i < size; ++i) { - CtMethod m = getMethod0(ifs[i], name, desc); + for (CtClass ctc : ifs) { + CtMethod m = getMethod0(ctc, name, desc); if (m != null) return m; } @@ -1263,35 +1289,36 @@ class CtClassType extends CtClass { return null; } + @Override public CtMethod[] getDeclaredMethods() { CtMember.Cache memCache = getMembers(); CtMember mth = memCache.methodHead(); CtMember mthTail = memCache.lastMethod(); - int num = CtMember.Cache.count(mth, mthTail); - CtMethod[] cms = new CtMethod[num]; - int i = 0; + List<CtMember> methods = new ArrayList<CtMember>(); while (mth != mthTail) { mth = mth.next(); - cms[i++] = (CtMethod)mth; + methods.add(mth); } - return cms; + return methods.toArray(new CtMethod[methods.size()]); } + @Override public CtMethod[] getDeclaredMethods(String name) throws NotFoundException { CtMember.Cache memCache = getMembers(); CtMember mth = memCache.methodHead(); CtMember mthTail = memCache.lastMethod(); - ArrayList methods = new ArrayList(); + List<CtMember> methods = new ArrayList<CtMember>(); while (mth != mthTail) { mth = mth.next(); if (mth.getName().equals(name)) - methods.add((CtMethod)mth); + methods.add(mth); } - return (CtMethod[]) methods.toArray(new CtMethod[methods.size()]); + return methods.toArray(new CtMethod[methods.size()]); } + @Override public CtMethod getDeclaredMethod(String name) throws NotFoundException { CtMember.Cache memCache = getMembers(); CtMember mth = memCache.methodHead(); @@ -1306,6 +1333,7 @@ class CtClassType extends CtClass { + getName()); } + @Override public CtMethod getDeclaredMethod(String name, CtClass[] params) throws NotFoundException { @@ -1325,12 +1353,14 @@ class CtClassType extends CtClass { + getName()); } + @Override public void addField(CtField f, String init) throws CannotCompileException { addField(f, CtField.Initializer.byExpr(init)); } + @Override public void addField(CtField f, CtField.Initializer init) throws CannotCompileException { @@ -1373,6 +1403,7 @@ class CtClassType extends CtClass { } } + @Override public void removeField(CtField f) throws NotFoundException { checkModify(); FieldInfo fi = f.getFieldInfo2(); @@ -1385,6 +1416,7 @@ class CtClassType extends CtClass { throw new NotFoundException(f.toString()); } + @Override public CtConstructor makeClassInitializer() throws CannotCompileException { @@ -1399,6 +1431,7 @@ class CtClassType extends CtClass { return getClassInitializer(); } + @Override public void addConstructor(CtConstructor c) throws CannotCompileException { @@ -1410,6 +1443,7 @@ class CtClassType extends CtClass { getClassFile2().addMethod(c.getMethodInfo2()); } + @Override public void removeConstructor(CtConstructor m) throws NotFoundException { checkModify(); MethodInfo mi = m.getMethodInfo2(); @@ -1422,6 +1456,7 @@ class CtClassType extends CtClass { throw new NotFoundException(m.toString()); } + @Override public void addMethod(CtMethod m) throws CannotCompileException { checkModify(); if (m.getDeclaringClass() != this) @@ -1442,7 +1477,9 @@ class CtClassType extends CtClass { setModifiers(getModifiers() | Modifier.ABSTRACT); } - public void removeMethod(CtMethod m) throws NotFoundException { + @Override + public void removeMethod(CtMethod m) throws NotFoundException + { checkModify(); MethodInfo mi = m.getMethodInfo2(); ClassFile cf = getClassFile2(); @@ -1454,52 +1491,53 @@ class CtClassType extends CtClass { throw new NotFoundException(m.toString()); } - public byte[] getAttribute(String name) { + @Override + public byte[] getAttribute(String name) + { AttributeInfo ai = getClassFile2().getAttribute(name); if (ai == null) return null; - else - return ai.get(); + return ai.get(); } - public void setAttribute(String name, byte[] data) { + @Override + public void setAttribute(String name, byte[] data) + { checkModify(); ClassFile cf = getClassFile2(); cf.addAttribute(new AttributeInfo(cf.getConstPool(), name, data)); } + @Override public void instrument(CodeConverter converter) throws CannotCompileException { checkModify(); ClassFile cf = getClassFile2(); ConstPool cp = cf.getConstPool(); - List list = cf.getMethods(); - int n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + List<MethodInfo> methods = cf.getMethods(); + for (MethodInfo minfo:methods) converter.doit(this, minfo, cp); - } } + @Override public void instrument(ExprEditor editor) throws CannotCompileException { checkModify(); ClassFile cf = getClassFile2(); - List list = cf.getMethods(); - int n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + List<MethodInfo> methods = cf.getMethods(); + for (MethodInfo minfo:methods) editor.doit(this, minfo); - } } /** * @see javassist.CtClass#prune() * @see javassist.CtClass#stopPruning(boolean) */ - public void prune() { + @Override + public void prune() + { if (wasPruned) return; @@ -1507,8 +1545,10 @@ class CtClassType extends CtClass { getClassFile2().prune(); } + @Override public void rebuildClassFile() { gcConstPool = true; } + @Override public void toBytecode(DataOutputStream out) throws CannotCompileException, IOException { @@ -1552,7 +1592,8 @@ class CtClassType extends CtClass { } } - private void dumpClassFile(ClassFile cf) throws IOException { + private void dumpClassFile(ClassFile cf) throws IOException + { DataOutputStream dump = makeFileOutput(debugDump); try { cf.write(dump); @@ -1564,13 +1605,16 @@ class CtClassType extends CtClass { /* See also checkModified() */ - private void checkPruned(String method) { + private void checkPruned(String method) + { if (wasPruned) throw new RuntimeException(method + "(): " + getName() + " was pruned."); } - public boolean stopPruning(boolean stop) { + @Override + public boolean stopPruning(boolean stop) + { boolean prev = !doPruning; doPruning = !stop; return prev; @@ -1655,10 +1699,8 @@ class CtClassType extends CtClass { return; ConstPool cp = cf.getConstPool(); - List list = cf.getMethods(); - int n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + List<MethodInfo> methods = cf.getMethods(); + for (MethodInfo minfo:methods) { if (minfo.isConstructor()) { CodeAttribute codeAttr = minfo.getCodeAttribute(); if (codeAttr != null) @@ -1729,19 +1771,20 @@ class CtClassType extends CtClass { // Methods used by CtNewWrappedMethod - Hashtable getHiddenMethods() { + Map<CtMethod,String> getHiddenMethods() { if (hiddenMethods == null) - hiddenMethods = new Hashtable(); + hiddenMethods = new Hashtable<CtMethod,String>(); return hiddenMethods; } int getUniqueNumber() { return uniqueNumberSeed++; } + @Override public String makeUniqueName(String prefix) { - HashMap table = new HashMap(); + Map<Object,CtClassType> table = new HashMap<Object,CtClassType>(); makeMemberList(table); - Set keys = table.keySet(); + Set<Object> keys = table.keySet(); String[] methods = new String[keys.size()]; keys.toArray(methods); @@ -1768,17 +1811,14 @@ class CtClassType extends CtClass { return true; } - private void makeMemberList(HashMap table) { + private void makeMemberList(Map<Object,CtClassType> table) { int mod = getModifiers(); if (Modifier.isAbstract(mod) || Modifier.isInterface(mod)) try { CtClass[] ifs = getInterfaces(); - int size = ifs.length; - for (int i = 0; i < size; i++) { - CtClass ic =ifs[i]; + for (CtClass ic : ifs) if (ic != null && ic instanceof CtClassType) ((CtClassType)ic).makeMemberList(table); - } } catch (NotFoundException e) {} @@ -1789,19 +1829,13 @@ class CtClassType extends CtClass { } catch (NotFoundException e) {} - List list = getClassFile2().getMethods(); - int n = list.size(); - for (int i = 0; i < n; i++) { - MethodInfo minfo = (MethodInfo)list.get(i); + List<MethodInfo> methods = getClassFile2().getMethods(); + for (MethodInfo minfo:methods) table.put(minfo.getName(), this); - } - list = getClassFile2().getFields(); - n = list.size(); - for (int i = 0; i < n; i++) { - FieldInfo finfo = (FieldInfo)list.get(i); + List<FieldInfo> fields = getClassFile2().getFields(); + for (FieldInfo finfo:fields) table.put(finfo.getName(), this); - } } } diff --git a/src/main/javassist/CtConstructor.java b/src/main/javassist/CtConstructor.java index 73bf531e..8e293ca2 100644 --- a/src/main/javassist/CtConstructor.java +++ b/src/main/javassist/CtConstructor.java @@ -16,9 +16,17 @@ package javassist; -import javassist.bytecode.*; -import javassist.compiler.Javac; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.ClassFile; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; import javassist.compiler.CompileError; +import javassist.compiler.Javac; /** * An instance of CtConstructor represents a constructor. @@ -122,6 +130,7 @@ public final class CtConstructor extends CtBehavior { * * @since 3.5 */ + @Override public String getLongName() { return getDeclaringClass().getName() + (isConstructor() ? Descriptor.toString(getSignature()) @@ -134,11 +143,11 @@ public final class CtConstructor extends CtBehavior { * constructor. If this object represents a class initializer, * then this method returns <code>"<clinit>"</code>. */ + @Override public String getName() { if (methodInfo.isStaticInitializer()) return MethodInfo.nameClinit; - else - return declaringClass.getSimpleName(); + return declaringClass.getSimpleName(); } /** @@ -148,6 +157,7 @@ public final class CtConstructor extends CtBehavior { * calling <code>super()</code> (the no-argument constructor of * the super class). */ + @Override public boolean isEmpty() { CodeAttribute ca = getMethodInfo2().getCodeAttribute(); if (ca == null) @@ -207,6 +217,7 @@ public final class CtConstructor extends CtBehavior { * constructor body does nothing except calling * <code>super()</code>. */ + @Override public void setBody(String src) throws CannotCompileException { if (src == null) if (isClassInitializer()) @@ -280,6 +291,7 @@ public final class CtConstructor extends CtBehavior { /* This method is called by addCatch() in CtBehavior. * super() and this() must not be in a try statement. */ + @Override int getStartPosOfBody(CodeAttribute ca) throws CannotCompileException { CodeIterator ci = ca.iterator(); try { diff --git a/src/main/javassist/CtField.java b/src/main/javassist/CtField.java index f9d8051b..892fff82 100644 --- a/src/main/javassist/CtField.java +++ b/src/main/javassist/CtField.java @@ -16,13 +16,23 @@ package javassist; -import javassist.bytecode.*; +import java.util.List; + +import javassist.bytecode.AccessFlag; +import javassist.bytecode.AnnotationsAttribute; +import javassist.bytecode.AttributeInfo; +import javassist.bytecode.Bytecode; +import javassist.bytecode.ClassFile; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.FieldInfo; +import javassist.bytecode.SignatureAttribute; +import javassist.compiler.CompileError; import javassist.compiler.Javac; import javassist.compiler.SymbolTable; -import javassist.compiler.CompileError; import javassist.compiler.ast.ASTree; -import javassist.compiler.ast.IntConst; import javassist.compiler.ast.DoubleConst; +import javassist.compiler.ast.IntConst; import javassist.compiler.ast.StringL; /** @@ -83,15 +93,12 @@ public class CtField extends CtMember { { this(src.fieldInfo.getDescriptor(), src.fieldInfo.getName(), declaring); - java.util.ListIterator iterator - = src.fieldInfo.getAttributes().listIterator(); FieldInfo fi = fieldInfo; fi.setAccessFlags(src.fieldInfo.getAccessFlags()); ConstPool cp = fi.getConstPool(); - while (iterator.hasNext()) { - AttributeInfo ainfo = (AttributeInfo)iterator.next(); + List<AttributeInfo> attributes = src.fieldInfo.getAttributes(); + for (AttributeInfo ainfo : attributes) fi.addAttribute(ainfo.copy(cp, null)); - } } private CtField(String typeDesc, String name, CtClass clazz) @@ -114,11 +121,13 @@ public class CtField extends CtMember { /** * Returns a String representation of the object. */ + @Override public String toString() { return getDeclaringClass().getName() + "." + getName() + ":" + fieldInfo.getDescriptor(); } + @Override protected void extendToString(StringBuffer buffer) { buffer.append(' '); buffer.append(getName()); @@ -126,18 +135,15 @@ public class CtField extends CtMember { buffer.append(fieldInfo.getDescriptor()); } - /* Javac.CtFieldWithInit overrides. - */ + /* Javac.CtFieldWithInit overrides. */ protected ASTree getInitAST() { return null; } - /* Called by CtClassType.addField(). - */ + /* Called by CtClassType.addField(). */ Initializer getInit() { ASTree tree = getInitAST(); if (tree == null) return null; - else - return Initializer.byExpr(tree); + return Initializer.byExpr(tree); } /** @@ -202,6 +208,7 @@ public class CtField extends CtMember { /** * Returns the class declaring the field. */ + @Override public CtClass getDeclaringClass() { // this is redundant but for javadoc. return super.getDeclaringClass(); @@ -210,6 +217,7 @@ public class CtField extends CtMember { /** * Returns the name of the field. */ + @Override public String getName() { return fieldInfo.getName(); } @@ -227,6 +235,7 @@ public class CtField extends CtMember { * * @see Modifier */ + @Override public int getModifiers() { return AccessFlag.toModifier(fieldInfo.getAccessFlags()); } @@ -236,6 +245,7 @@ public class CtField extends CtMember { * * @see Modifier */ + @Override public void setModifiers(int mod) { declaringClass.checkModify(); fieldInfo.setAccessFlags(AccessFlag.of(mod)); @@ -248,6 +258,7 @@ public class CtField extends CtMember { * @return <code>true</code> if the annotation is found, otherwise <code>false</code>. * @since 3.21 */ + @Override public boolean hasAnnotation(String typeName) { FieldInfo fi = getFieldInfo2(); AnnotationsAttribute ainfo = (AnnotationsAttribute) @@ -269,7 +280,8 @@ public class CtField extends CtMember { * @return the annotation if found, otherwise <code>null</code>. * @since 3.11 */ - public Object getAnnotation(Class clz) throws ClassNotFoundException { + @Override + public Object getAnnotation(Class<?> clz) throws ClassNotFoundException { FieldInfo fi = getFieldInfo2(); AnnotationsAttribute ainfo = (AnnotationsAttribute) fi.getAttribute(AnnotationsAttribute.invisibleTag); @@ -286,6 +298,7 @@ public class CtField extends CtMember { * @see #getAvailableAnnotations() * @since 3.1 */ + @Override public Object[] getAnnotations() throws ClassNotFoundException { return getAnnotations(false); } @@ -299,6 +312,7 @@ public class CtField extends CtMember { * @see #getAnnotations() * @since 3.3 */ + @Override public Object[] getAvailableAnnotations(){ try { return getAnnotations(true); @@ -332,6 +346,7 @@ public class CtField extends CtMember { * @see javassist.bytecode.Descriptor * @see #getGenericSignature() */ + @Override public String getSignature() { return fieldInfo.getDescriptor(); } @@ -343,6 +358,7 @@ public class CtField extends CtMember { * @see SignatureAttribute#toFieldSignature(String) * @since 3.17 */ + @Override public String getGenericSignature() { SignatureAttribute sa = (SignatureAttribute)fieldInfo.getAttribute(SignatureAttribute.tag); @@ -359,6 +375,7 @@ public class CtField extends CtMember { * @see javassist.bytecode.SignatureAttribute.ObjectType#encode() * @since 3.17 */ + @Override public void setGenericSignature(String sig) { declaringClass.checkModify(); fieldInfo.addAttribute(new SignatureAttribute(fieldInfo.getConstPool(), sig)); @@ -426,8 +443,7 @@ public class CtField extends CtMember { // "Z" means boolean type. if ("Z".equals(fieldInfo.getDescriptor())) return Boolean.valueOf(value != 0); - else - return Integer.valueOf(value); + return Integer.valueOf(value); case ConstPool.CONST_String : return cp.getStringInfo(index); default : @@ -447,12 +463,12 @@ public class CtField extends CtMember { * * @param name attribute name */ + @Override public byte[] getAttribute(String name) { AttributeInfo ai = fieldInfo.getAttribute(name); if (ai == null) return null; - else - return ai.get(); + return ai.get(); } /** @@ -465,6 +481,7 @@ public class CtField extends CtMember { * @param name attribute name * @param data attribute value */ + @Override public void setAttribute(String name, byte[] data) { declaringClass.checkModify(); fieldInfo.addAttribute(new AttributeInfo(fieldInfo.getConstPool(), @@ -854,6 +871,7 @@ public class CtField extends CtMember { static abstract class CodeInitializer0 extends Initializer { abstract void compileExpr(Javac drv) throws CompileError; + @Override int compile(CtClass type, String name, Bytecode code, CtClass[] parameters, Javac drv) throws CannotCompileException @@ -869,6 +887,7 @@ public class CtField extends CtMember { } } + @Override int compileIfStatic(CtClass type, String name, Bytecode code, Javac drv) throws CannotCompileException { @@ -887,9 +906,9 @@ public class CtField extends CtMember { if (tree instanceof IntConst) { long value = ((IntConst)tree).get(); if (type == CtClass.doubleType) - return cp.addDoubleInfo((double)value); + return cp.addDoubleInfo(value); else if (type == CtClass.floatType) - return cp.addFloatInfo((float)value); + return cp.addFloatInfo(value); else if (type == CtClass.longType) return cp.addLongInfo(value); else if (type != CtClass.voidType) @@ -916,10 +935,12 @@ public class CtField extends CtMember { CodeInitializer(String expr) { expression = expr; } + @Override void compileExpr(Javac drv) throws CompileError { drv.compileExpr(expression); } + @Override int getConstantValue(ConstPool cp, CtClass type) { try { ASTree t = Javac.parseExpr(expression, new SymbolTable()); @@ -936,10 +957,12 @@ public class CtField extends CtMember { PtreeInitializer(ASTree expr) { expression = expr; } + @Override void compileExpr(Javac drv) throws CompileError { drv.compileExpr(expression); } + @Override int getConstantValue(ConstPool cp, CtClass type) { return getConstantValue2(cp, type, expression); } @@ -954,6 +977,7 @@ public class CtField extends CtMember { ParamInitializer() {} + @Override int compile(CtClass type, String name, Bytecode code, CtClass[] parameters, Javac drv) throws CannotCompileException @@ -965,8 +989,7 @@ public class CtField extends CtMember { code.addPutfield(Bytecode.THIS, name, Descriptor.of(type)); return s; // stack size } - else - return 0; // do not initialize + return 0; // do not initialize } /** @@ -998,6 +1021,7 @@ public class CtField extends CtMember { return k; } + @Override int compileIfStatic(CtClass type, String name, Bytecode code, Javac drv) throws CannotCompileException { @@ -1019,6 +1043,7 @@ public class CtField extends CtMember { * Produces codes in which a new object is created and assigned to * the field as the initial value. */ + @Override int compile(CtClass type, String name, Bytecode code, CtClass[] parameters, Javac drv) throws CannotCompileException @@ -1053,16 +1078,17 @@ public class CtField extends CtMember { return "(Ljava/lang/Object;[Ljava/lang/Object;)V"; else return "(Ljava/lang/Object;)V"; - else - if (withConstructorParams) - return desc3; - else - return "(Ljava/lang/Object;[Ljava/lang/String;)V"; + + if (withConstructorParams) + return desc3; + + return "(Ljava/lang/Object;[Ljava/lang/String;)V"; } /** * Produces codes for a static field. */ + @Override int compileIfStatic(CtClass type, String name, Bytecode code, Javac drv) throws CannotCompileException { @@ -1115,6 +1141,7 @@ public class CtField extends CtMember { * Produces codes in which a new object is created and assigned to * the field as the initial value. */ + @Override int compile(CtClass type, String name, Bytecode code, CtClass[] parameters, Javac drv) throws CannotCompileException @@ -1149,16 +1176,17 @@ public class CtField extends CtMember { return "(Ljava/lang/Object;[Ljava/lang/Object;)"; else return "(Ljava/lang/Object;)"; - else - if (withConstructorParams) - return desc3; - else - return "(Ljava/lang/Object;[Ljava/lang/String;)"; + + if (withConstructorParams) + return desc3; + + return "(Ljava/lang/Object;[Ljava/lang/String;)"; } /** * Produces codes for a static field. */ + @Override int compileIfStatic(CtClass type, String name, Bytecode code, Javac drv) throws CannotCompileException { @@ -1184,12 +1212,14 @@ public class CtField extends CtMember { IntInitializer(int v) { value = v; } + @Override void check(String desc) throws CannotCompileException { char c = desc.charAt(0); if (c != 'I' && c != 'S' && c != 'B' && c != 'C' && c != 'Z') throw new CannotCompileException("type mismatch"); } + @Override int compile(CtClass type, String name, Bytecode code, CtClass[] parameters, Javac drv) throws CannotCompileException @@ -1200,6 +1230,7 @@ public class CtField extends CtMember { return 2; // stack size } + @Override int compileIfStatic(CtClass type, String name, Bytecode code, Javac drv) throws CannotCompileException { @@ -1208,6 +1239,7 @@ public class CtField extends CtMember { return 1; // stack size } + @Override int getConstantValue(ConstPool cp, CtClass type) { return cp.addIntegerInfo(value); } @@ -1218,11 +1250,13 @@ public class CtField extends CtMember { LongInitializer(long v) { value = v; } + @Override void check(String desc) throws CannotCompileException { if (!desc.equals("J")) throw new CannotCompileException("type mismatch"); } + @Override int compile(CtClass type, String name, Bytecode code, CtClass[] parameters, Javac drv) throws CannotCompileException @@ -1233,6 +1267,7 @@ public class CtField extends CtMember { return 3; // stack size } + @Override int compileIfStatic(CtClass type, String name, Bytecode code, Javac drv) throws CannotCompileException { @@ -1241,11 +1276,11 @@ public class CtField extends CtMember { return 2; // stack size } + @Override int getConstantValue(ConstPool cp, CtClass type) { if (type == CtClass.longType) return cp.addLongInfo(value); - else - return 0; + return 0; } } @@ -1254,11 +1289,13 @@ public class CtField extends CtMember { FloatInitializer(float v) { value = v; } + @Override void check(String desc) throws CannotCompileException { if (!desc.equals("F")) throw new CannotCompileException("type mismatch"); } + @Override int compile(CtClass type, String name, Bytecode code, CtClass[] parameters, Javac drv) throws CannotCompileException @@ -1269,6 +1306,7 @@ public class CtField extends CtMember { return 3; // stack size } + @Override int compileIfStatic(CtClass type, String name, Bytecode code, Javac drv) throws CannotCompileException { @@ -1277,11 +1315,11 @@ public class CtField extends CtMember { return 2; // stack size } + @Override int getConstantValue(ConstPool cp, CtClass type) { if (type == CtClass.floatType) return cp.addFloatInfo(value); - else - return 0; + return 0; } } @@ -1290,11 +1328,13 @@ public class CtField extends CtMember { DoubleInitializer(double v) { value = v; } + @Override void check(String desc) throws CannotCompileException { if (!desc.equals("D")) throw new CannotCompileException("type mismatch"); } + @Override int compile(CtClass type, String name, Bytecode code, CtClass[] parameters, Javac drv) throws CannotCompileException @@ -1305,6 +1345,7 @@ public class CtField extends CtMember { return 3; // stack size } + @Override int compileIfStatic(CtClass type, String name, Bytecode code, Javac drv) throws CannotCompileException { @@ -1313,11 +1354,11 @@ public class CtField extends CtMember { return 2; // stack size } + @Override int getConstantValue(ConstPool cp, CtClass type) { if (type == CtClass.doubleType) return cp.addDoubleInfo(value); - else - return 0; + return 0; } } @@ -1326,6 +1367,7 @@ public class CtField extends CtMember { StringInitializer(String v) { value = v; } + @Override int compile(CtClass type, String name, Bytecode code, CtClass[] parameters, Javac drv) throws CannotCompileException @@ -1336,6 +1378,7 @@ public class CtField extends CtMember { return 2; // stack size } + @Override int compileIfStatic(CtClass type, String name, Bytecode code, Javac drv) throws CannotCompileException { @@ -1344,11 +1387,11 @@ public class CtField extends CtMember { return 1; // stack size } + @Override int getConstantValue(ConstPool cp, CtClass type) { if (type.getName().equals(javaLangString)) return cp.addStringInfo(value); - else - return 0; + return 0; } } @@ -1366,6 +1409,7 @@ public class CtField extends CtMember { code.addAnewarray(type, size); } + @Override int compile(CtClass type, String name, Bytecode code, CtClass[] parameters, Javac drv) throws CannotCompileException @@ -1376,6 +1420,7 @@ public class CtField extends CtMember { return 2; // stack size } + @Override int compileIfStatic(CtClass type, String name, Bytecode code, Javac drv) throws CannotCompileException { @@ -1391,11 +1436,13 @@ public class CtField extends CtMember { MultiArrayInitializer(CtClass t, int[] d) { type = t; dim = d; } + @Override void check(String desc) throws CannotCompileException { if (desc.charAt(0) != '[') throw new CannotCompileException("type mismatch"); } + @Override int compile(CtClass type, String name, Bytecode code, CtClass[] parameters, Javac drv) throws CannotCompileException @@ -1406,6 +1453,7 @@ public class CtField extends CtMember { return s + 1; // stack size } + @Override int compileIfStatic(CtClass type, String name, Bytecode code, Javac drv) throws CannotCompileException { diff --git a/src/main/javassist/CtMember.java b/src/main/javassist/CtMember.java index 3c5da768..8de480c9 100644 --- a/src/main/javassist/CtMember.java +++ b/src/main/javassist/CtMember.java @@ -29,20 +29,33 @@ public abstract class CtMember { * at the same time. */ static class Cache extends CtMember { + @Override protected void extendToString(StringBuffer buffer) {} + @Override public boolean hasAnnotation(String clz) { return false; } - public Object getAnnotation(Class clz) + @Override + public Object getAnnotation(Class<?> clz) throws ClassNotFoundException { return null; } + @Override public Object[] getAnnotations() throws ClassNotFoundException { return null; } + @Override public byte[] getAttribute(String name) { return null; } + @Override public Object[] getAvailableAnnotations() { return null; } + @Override public int getModifiers() { return 0; } + @Override public String getName() { return null; } + @Override public String getSignature() { return null; } + @Override public void setAttribute(String name, byte[] data) {} + @Override public void setModifiers(int mod) {} + @Override public String getGenericSignature() { return null; } + @Override public void setGenericSignature(String sig) {} private CtMember methodTail; @@ -120,8 +133,7 @@ public abstract class CtMember { break; } - else - m = m.next; + m = m.next; } } } @@ -141,6 +153,7 @@ public abstract class CtMember { */ void nameReplaced() {} + @Override public String toString() { StringBuffer buffer = new StringBuffer(getClass().getName()); buffer.append("@"); @@ -214,7 +227,7 @@ public abstract class CtMember { * @return <code>true</code> if the annotation is found, otherwise <code>false</code>. * @since 3.11 */ - public boolean hasAnnotation(Class clz) { + public boolean hasAnnotation(Class<?> clz) { return hasAnnotation(clz.getName()); } @@ -238,7 +251,7 @@ public abstract class CtMember { * @return the annotation if found, otherwise <code>null</code>. * @since 3.11 */ - public abstract Object getAnnotation(Class annotationType) throws ClassNotFoundException; + public abstract Object getAnnotation(Class<?> annotationType) throws ClassNotFoundException; /** * Returns the annotations associated with this member. diff --git a/src/main/javassist/CtMethod.java b/src/main/javassist/CtMethod.java index 2f657dfa..3702e351 100644 --- a/src/main/javassist/CtMethod.java +++ b/src/main/javassist/CtMethod.java @@ -16,7 +16,15 @@ package javassist; -import javassist.bytecode.*; +import javassist.bytecode.AccessFlag; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; /** * An instance of <code>CtMethod</code> represents a method. @@ -155,6 +163,7 @@ public final class CtMethod extends CtBehavior { * If two methods have the same name and signature, then * the hash codes for the two methods are equal. */ + @Override public int hashCode() { return getStringRep().hashCode(); } @@ -163,6 +172,7 @@ public final class CtMethod extends CtBehavior { * This method is invoked when setName() or replaceClassName() * in CtClass is called. */ + @Override void nameReplaced() { cachedStringRep = null; } @@ -181,6 +191,7 @@ public final class CtMethod extends CtBehavior { * Indicates whether <code>obj</code> has the same name and the * same signature as this method. */ + @Override public boolean equals(Object obj) { return obj != null && obj instanceof CtMethod && ((CtMethod)obj).getStringRep().equals(getStringRep()); @@ -192,6 +203,7 @@ public final class CtMethod extends CtBehavior { * * @since 3.5 */ + @Override public String getLongName() { return getDeclaringClass().getName() + "." + getName() + Descriptor.toString(getSignature()); @@ -200,6 +212,7 @@ public final class CtMethod extends CtBehavior { /** * Obtains the name of this method. */ + @Override public String getName() { return methodInfo.getName(); } @@ -223,6 +236,7 @@ public final class CtMethod extends CtBehavior { * Returns true if the method body is empty, that is, <code>{}</code>. * It also returns true if the method is an abstract method. */ + @Override public boolean isEmpty() { CodeAttribute ca = getMethodInfo2().getCodeAttribute(); if (ca == null) // abstract or native @@ -380,15 +394,18 @@ public final class CtMethod extends CtBehavior { param = i; } + @Override int compile(Bytecode code) throws CannotCompileException { code.addIconst(param); return 1; } + @Override String descriptor() { return "([Ljava/lang/Object;I)Ljava/lang/Object;"; } + @Override String constDescriptor() { return "([Ljava/lang/Object;I)V"; } @@ -401,15 +418,18 @@ public final class CtMethod extends CtBehavior { param = l; } + @Override int compile(Bytecode code) throws CannotCompileException { code.addLconst(param); return 2; } + @Override String descriptor() { return "([Ljava/lang/Object;J)Ljava/lang/Object;"; } + @Override String constDescriptor() { return "([Ljava/lang/Object;J)V"; } @@ -422,15 +442,18 @@ public final class CtMethod extends CtBehavior { param = s; } + @Override int compile(Bytecode code) throws CannotCompileException { code.addLdc(param); return 1; } + @Override String descriptor() { return "([Ljava/lang/Object;Ljava/lang/String;)Ljava/lang/Object;"; } + @Override String constDescriptor() { return "([Ljava/lang/Object;Ljava/lang/String;)V"; } diff --git a/src/main/javassist/CtNewClass.java b/src/main/javassist/CtNewClass.java index c809522b..b0a14806 100644 --- a/src/main/javassist/CtNewClass.java +++ b/src/main/javassist/CtNewClass.java @@ -18,6 +18,7 @@ package javassist; import java.io.DataOutputStream; import java.io.IOException; + import javassist.bytecode.ClassFile; class CtNewClass extends CtClassType { @@ -43,6 +44,7 @@ class CtNewClass extends CtClassType { hasConstructor = isInterface; } + @Override protected void extendToString(StringBuffer buffer) { if (hasConstructor) buffer.append("hasConstructor "); @@ -50,6 +52,7 @@ class CtNewClass extends CtClassType { super.extendToString(buffer); } + @Override public void addConstructor(CtConstructor c) throws CannotCompileException { @@ -57,6 +60,7 @@ class CtNewClass extends CtClassType { super.addConstructor(c); } + @Override public void toBytecode(DataOutputStream out) throws CannotCompileException, IOException { @@ -117,8 +121,7 @@ class CtNewClass extends CtClassType { String pname2 = superclazz.getPackageName(); if (pname == null) return pname2 == null; - else - return pname.equals(pname2); + return pname.equals(pname2); } return true; diff --git a/src/main/javassist/CtNewConstructor.java b/src/main/javassist/CtNewConstructor.java index ecec642f..9f4225f1 100644 --- a/src/main/javassist/CtNewConstructor.java +++ b/src/main/javassist/CtNewConstructor.java @@ -16,10 +16,11 @@ package javassist; -import javassist.bytecode.*; -import javassist.compiler.Javac; -import javassist.compiler.CompileError; import javassist.CtMethod.ConstParameter; +import javassist.bytecode.Bytecode; +import javassist.bytecode.ConstPool; +import javassist.compiler.CompileError; +import javassist.compiler.Javac; /** * A collection of static methods for creating a <code>CtConstructor</code>. diff --git a/src/main/javassist/CtNewMethod.java b/src/main/javassist/CtNewMethod.java index 48d8629a..3daaa026 100644 --- a/src/main/javassist/CtNewMethod.java +++ b/src/main/javassist/CtNewMethod.java @@ -16,10 +16,15 @@ package javassist; -import javassist.bytecode.*; -import javassist.compiler.Javac; -import javassist.compiler.CompileError; import javassist.CtMethod.ConstParameter; +import javassist.bytecode.AccessFlag; +import javassist.bytecode.Bytecode; +import javassist.bytecode.ConstPool; +import javassist.bytecode.ExceptionsAttribute; +import javassist.bytecode.FieldInfo; +import javassist.bytecode.MethodInfo; +import javassist.compiler.CompileError; +import javassist.compiler.Javac; /** * A collection of static methods for creating a <code>CtMethod</code>. diff --git a/src/main/javassist/CtNewWrappedConstructor.java b/src/main/javassist/CtNewWrappedConstructor.java index 7163f1ce..8e6b3654 100644 --- a/src/main/javassist/CtNewWrappedConstructor.java +++ b/src/main/javassist/CtNewWrappedConstructor.java @@ -16,8 +16,10 @@ package javassist; -import javassist.bytecode.*; import javassist.CtMethod.ConstParameter; +import javassist.bytecode.Bytecode; +import javassist.bytecode.ClassFile; +import javassist.bytecode.Descriptor; class CtNewWrappedConstructor extends CtNewWrappedMethod { private static final int PASS_NONE = CtNewConstructor.PASS_NONE; diff --git a/src/main/javassist/CtNewWrappedMethod.java b/src/main/javassist/CtNewWrappedMethod.java index 66504bed..2e6a6a87 100644 --- a/src/main/javassist/CtNewWrappedMethod.java +++ b/src/main/javassist/CtNewWrappedMethod.java @@ -16,10 +16,16 @@ package javassist; -import javassist.bytecode.*; -import javassist.compiler.JvstCodeGen; -import java.util.Hashtable; +import java.util.Map; + import javassist.CtMethod.ConstParameter; +import javassist.bytecode.AccessFlag; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.ClassFile; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.SyntheticAttribute; +import javassist.compiler.JvstCodeGen; class CtNewWrappedMethod { @@ -139,8 +145,8 @@ class CtNewWrappedMethod { CtMethod src) throws BadBytecode, CannotCompileException { - Hashtable bodies = clazz.getHiddenMethods(); - String bodyname = (String)bodies.get(src); + Map<CtMethod,String> bodies = clazz.getHiddenMethods(); + String bodyname = bodies.get(src); if (bodyname == null) { do { bodyname = addedWrappedMethod + clazz.getUniqueNumber(); diff --git a/src/main/javassist/CtPrimitiveType.java b/src/main/javassist/CtPrimitiveType.java index bcf71310..24b55010 100644 --- a/src/main/javassist/CtPrimitiveType.java +++ b/src/main/javassist/CtPrimitiveType.java @@ -47,6 +47,7 @@ public final class CtPrimitiveType extends CtClass { * Java type: boolean, byte, char, short, int, long, float, double, * or void. */ + @Override public boolean isPrimitive() { return true; } /** @@ -55,6 +56,7 @@ public final class CtPrimitiveType extends CtClass { * * @see Modifier */ + @Override public int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } diff --git a/src/main/javassist/Loader.java b/src/main/javassist/Loader.java index 93f3ce34..cbbf09e5 100644 --- a/src/main/javassist/Loader.java +++ b/src/main/javassist/Loader.java @@ -16,10 +16,12 @@ package javassist; -import java.io.*; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.security.ProtectionDomain; +import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; -import java.security.ProtectionDomain; /** * The class loader for Javassist. @@ -134,8 +136,8 @@ import java.security.ProtectionDomain; * @see javassist.Translator */ public class Loader extends ClassLoader { - private Hashtable notDefinedHere; // must be atomic. - private Vector notDefinedPackages; // must be atomic. + private Hashtable<String,ClassLoader> notDefinedHere; // must be atomic. + private Vector<String> notDefinedPackages; // must be atomic. private ClassPool source; private Translator translator; private ProtectionDomain domain; @@ -182,8 +184,8 @@ public class Loader extends ClassLoader { } private void init(ClassPool cp) { - notDefinedHere = new Hashtable(); - notDefinedPackages = new Vector(); + notDefinedHere = new Hashtable<String,ClassLoader>(); + notDefinedPackages = new Vector<String>(); source = cp; translator = null; domain = null; @@ -266,14 +268,8 @@ public class Loader extends ClassLoader { * to the target {@code main()}. */ public void run(String[] args) throws Throwable { - int n = args.length - 1; - if (n >= 0) { - String[] args2 = new String[n]; - for (int i = 0; i < n; ++i) - args2[i] = args[i + 1]; - - run(args[0], args2); - } + if (args.length >= 1) + run(args[0], Arrays.copyOfRange(args, 1, args.length)); } /** @@ -283,13 +279,13 @@ public class Loader extends ClassLoader { * @param args parameters passed to <code>main()</code>. */ public void run(String classname, String[] args) throws Throwable { - Class c = loadClass(classname); + Class<?> c = loadClass(classname); try { - c.getDeclaredMethod("main", new Class[] { String[].class }).invoke( + c.getDeclaredMethod("main", new Class<?>[] { String[].class }).invoke( null, new Object[] { args }); } - catch (java.lang.reflect.InvocationTargetException e) { + catch (InvocationTargetException e) { throw e.getTargetException(); } } @@ -297,11 +293,12 @@ public class Loader extends ClassLoader { /** * Requests the class loader to load a class. */ - protected Class loadClass(String name, boolean resolve) + @Override + protected Class<?> loadClass(String name, boolean resolve) throws ClassFormatError, ClassNotFoundException { name = name.intern(); synchronized (name) { - Class c = findLoadedClass(name); + Class<?> c = findLoadedClass(name); if (c == null) c = loadClassByDelegation(name); @@ -330,7 +327,8 @@ public class Loader extends ClassLoader { * @throws ClassNotFoundException if an exception is thrown while * obtaining a class file. */ - protected Class findClass(String name) throws ClassNotFoundException { + @Override + protected Class<?> findClass(String name) throws ClassNotFoundException { byte[] classfile; try { if (source != null) { @@ -362,7 +360,7 @@ public class Loader extends ClassLoader { int i = name.lastIndexOf('.'); if (i != -1) { String pname = name.substring(0, i); - if (getPackage(pname) == null) + if (getDefinedPackage(pname) == null) try { definePackage( pname, null, null, null, null, null, null, null); @@ -375,11 +373,10 @@ public class Loader extends ClassLoader { if (domain == null) return defineClass(name, classfile, 0, classfile.length); - else - return defineClass(name, classfile, 0, classfile.length, domain); + return defineClass(name, classfile, 0, classfile.length, domain); } - protected Class loadClassByDelegation(String name) + protected Class<?> loadClassByDelegation(String name) throws ClassNotFoundException { /* The swing components must be loaded by a system @@ -392,7 +389,7 @@ public class Loader extends ClassLoader { * by this class loader. */ - Class c = null; + Class<?> c = null; if (doDelegation) if (name.startsWith("java.") || name.startsWith("javax.") @@ -407,24 +404,22 @@ public class Loader extends ClassLoader { } private boolean notDelegated(String name) { - if (notDefinedHere.get(name) != null) + if (notDefinedHere.containsKey(name)) return true; - int n = notDefinedPackages.size(); - for (int i = 0; i < n; ++i) - if (name.startsWith((String)notDefinedPackages.elementAt(i))) + for (String pack : notDefinedPackages) + if (name.startsWith(pack)) return true; return false; } - protected Class delegateToParent(String classname) + protected Class<?> delegateToParent(String classname) throws ClassNotFoundException { ClassLoader cl = getParent(); if (cl != null) return cl.loadClass(classname); - else - return findSystemClass(classname); + return findSystemClass(classname); } } diff --git a/src/main/javassist/LoaderClassPath.java b/src/main/javassist/LoaderClassPath.java index 299fdb85..6807dfa3 100644 --- a/src/main/javassist/LoaderClassPath.java +++ b/src/main/javassist/LoaderClassPath.java @@ -17,8 +17,9 @@ package javassist; import java.io.InputStream; -import java.net.URL; +import java.lang.ref.Reference; import java.lang.ref.WeakReference; +import java.net.URL; /** * A class search-path representing a class loader. @@ -44,21 +45,18 @@ import java.lang.ref.WeakReference; * @see ClassClassPath */ public class LoaderClassPath implements ClassPath { - private WeakReference clref; + private Reference<ClassLoader> clref; /** * Creates a search path representing a class loader. */ public LoaderClassPath(ClassLoader cl) { - clref = new WeakReference(cl); + clref = new WeakReference<ClassLoader>(cl); } + @Override public String toString() { - Object cl = null; - if (clref != null) - cl = clref.get(); - - return cl == null ? "<null>" : cl.toString(); + return clref.get() == null ? "<null>" : clref.get().toString(); } /** @@ -66,15 +64,14 @@ public class LoaderClassPath implements ClassPath { * This method calls <code>getResourceAsStream(String)</code> * on the class loader. */ + @Override public InputStream openClassfile(String classname) throws NotFoundException { String cname = classname.replace('.', '/') + ".class"; - ClassLoader cl = (ClassLoader)clref.get(); + ClassLoader cl = clref.get(); if (cl == null) return null; // not found - else { - InputStream is = cl.getResourceAsStream(cname); - return is; - } + InputStream is = cl.getResourceAsStream(cname); + return is; } /** @@ -84,14 +81,13 @@ public class LoaderClassPath implements ClassPath { * * @return null if the class file could not be found. */ + @Override public URL find(String classname) { String cname = classname.replace('.', '/') + ".class"; - ClassLoader cl = (ClassLoader)clref.get(); + ClassLoader cl = clref.get(); if (cl == null) return null; // not found - else { - URL url = cl.getResource(cname); - return url; - } + URL url = cl.getResource(cname); + return url; } } diff --git a/src/main/javassist/NotFoundException.java b/src/main/javassist/NotFoundException.java index 00325cbb..135d7904 100644 --- a/src/main/javassist/NotFoundException.java +++ b/src/main/javassist/NotFoundException.java @@ -20,6 +20,9 @@ package javassist; * Signals that something could not be found. */ public class NotFoundException extends Exception { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public NotFoundException(String msg) { super(msg); } diff --git a/src/main/javassist/SerialVersionUID.java b/src/main/javassist/SerialVersionUID.java index c1a93bb6..ebb18bfa 100644 --- a/src/main/javassist/SerialVersionUID.java +++ b/src/main/javassist/SerialVersionUID.java @@ -16,12 +16,17 @@ package javassist; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; import java.lang.reflect.Modifier; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Comparator; -import javassist.bytecode.*; -import java.util.*; -import java.security.*; +import javassist.bytecode.ClassFile; +import javassist.bytecode.Descriptor; /** * Utility for calculating serialVersionUIDs for Serializable classes. @@ -108,16 +113,15 @@ public class SerialVersionUID { // fields. CtField[] fields = clazz.getDeclaredFields(); - Arrays.sort(fields, new Comparator() { - public int compare(Object o1, Object o2) { - CtField field1 = (CtField)o1; - CtField field2 = (CtField)o2; + Arrays.sort(fields, new Comparator<CtField>() { + @Override + public int compare(CtField field1, CtField field2) { return field1.getName().compareTo(field2.getName()); } }); for (int i = 0; i < fields.length; i++) { - CtField field = (CtField) fields[i]; + CtField field = fields[i]; int mods = field.getModifiers(); if (((mods & Modifier.PRIVATE) == 0) || ((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0)) { @@ -136,10 +140,9 @@ public class SerialVersionUID { // constructors. CtConstructor[] constructors = clazz.getDeclaredConstructors(); - Arrays.sort(constructors, new Comparator() { - public int compare(Object o1, Object o2) { - CtConstructor c1 = (CtConstructor)o1; - CtConstructor c2 = (CtConstructor)o2; + Arrays.sort(constructors, new Comparator<CtConstructor>() { + @Override + public int compare(CtConstructor c1, CtConstructor c2) { return c1.getMethodInfo2().getDescriptor().compareTo( c2.getMethodInfo2().getDescriptor()); } @@ -157,10 +160,9 @@ public class SerialVersionUID { } // methods. - Arrays.sort(methods, new Comparator() { - public int compare(Object o1, Object o2) { - CtMethod m1 = (CtMethod)o1; - CtMethod m2 = (CtMethod)o2; + Arrays.sort(methods, new Comparator<CtMethod>() { + @Override + public int compare(CtMethod m1, CtMethod m2) { int value = m1.getName().compareTo(m2.getName()); if (value == 0) value = m1.getMethodInfo2().getDescriptor() diff --git a/src/main/javassist/URLClassPath.java b/src/main/javassist/URLClassPath.java index 5eeef3a9..8e81c783 100644 --- a/src/main/javassist/URLClassPath.java +++ b/src/main/javassist/URLClassPath.java @@ -16,8 +16,11 @@ package javassist; -import java.io.*; -import java.net.*; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; /** * A class search-path specified with URL (http). @@ -65,6 +68,7 @@ public class URLClassPath implements ClassPath { this.packageName = packageName; } + @Override public String toString() { return hostname + ":" + port + directory; } @@ -74,6 +78,7 @@ public class URLClassPath implements ClassPath { * * @return null if the class file could not be found. */ + @Override public InputStream openClassfile(String classname) { try { URLConnection con = openClassfile0(classname); @@ -90,8 +95,7 @@ public class URLClassPath implements ClassPath { = directory + classname.replace('.', '/') + ".class"; return fetchClass0(hostname, port, jarname); } - else - return null; // not found + return null; // not found } /** @@ -99,6 +103,7 @@ public class URLClassPath implements ClassPath { * * @return null if the class file could not be obtained. */ + @Override public URL find(String classname) { try { URLConnection con = openClassfile0(classname); diff --git a/src/main/javassist/bytecode/AnnotationDefaultAttribute.java b/src/main/javassist/bytecode/AnnotationDefaultAttribute.java index 7379b412..43021ecf 100644 --- a/src/main/javassist/bytecode/AnnotationDefaultAttribute.java +++ b/src/main/javassist/bytecode/AnnotationDefaultAttribute.java @@ -16,15 +16,15 @@ package javassist.bytecode; -import javassist.CtClass; -import javassist.bytecode.annotation.AnnotationsWriter; -import javassist.bytecode.annotation.MemberValue; - import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.util.Map; +import javassist.CtClass; +import javassist.bytecode.annotation.AnnotationsWriter; +import javassist.bytecode.annotation.MemberValue; + /** * A class representing <code>AnnotationDefault_attribute</code>. * @@ -104,7 +104,8 @@ public class AnnotationDefaultAttribute extends AttributeInfo { /** * Copies this attribute and returns a new copy. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { AnnotationsAttribute.Copier copier = new AnnotationsAttribute.Copier(info, constPool, newCp, classnames); try { @@ -154,6 +155,7 @@ public class AnnotationDefaultAttribute extends AttributeInfo { /** * Returns a string representation of this object. */ + @Override public String toString() { return getDefaultValue().toString(); } diff --git a/src/main/javassist/bytecode/AnnotationsAttribute.java b/src/main/javassist/bytecode/AnnotationsAttribute.java index be69fe8b..73fcd73a 100644 --- a/src/main/javassist/bytecode/AnnotationsAttribute.java +++ b/src/main/javassist/bytecode/AnnotationsAttribute.java @@ -16,12 +16,28 @@ package javassist.bytecode; -import java.util.Map; -import java.util.HashMap; -import java.io.IOException; -import java.io.DataInputStream; import java.io.ByteArrayOutputStream; -import javassist.bytecode.annotation.*; +import java.io.DataInputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import javassist.bytecode.annotation.Annotation; +import javassist.bytecode.annotation.AnnotationMemberValue; +import javassist.bytecode.annotation.AnnotationsWriter; +import javassist.bytecode.annotation.ArrayMemberValue; +import javassist.bytecode.annotation.BooleanMemberValue; +import javassist.bytecode.annotation.ByteMemberValue; +import javassist.bytecode.annotation.CharMemberValue; +import javassist.bytecode.annotation.ClassMemberValue; +import javassist.bytecode.annotation.DoubleMemberValue; +import javassist.bytecode.annotation.EnumMemberValue; +import javassist.bytecode.annotation.FloatMemberValue; +import javassist.bytecode.annotation.IntegerMemberValue; +import javassist.bytecode.annotation.LongMemberValue; +import javassist.bytecode.annotation.MemberValue; +import javassist.bytecode.annotation.ShortMemberValue; +import javassist.bytecode.annotation.StringMemberValue; /** * A class representing @@ -160,7 +176,8 @@ public class AnnotationsAttribute extends AttributeInfo { /** * Copies this attribute and returns a new copy. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { Copier copier = new Copier(info, constPool, newCp, classnames); try { copier.annotationArray(); @@ -297,13 +314,15 @@ public class AnnotationsAttribute extends AttributeInfo { * @param oldname a JVM class name. * @param newname a JVM class name. */ + @Override void renameClass(String oldname, String newname) { - HashMap map = new HashMap(); + Map<String,String> map = new HashMap<String,String>(); map.put(oldname, newname); renameClass(map); } - void renameClass(Map classnames) { + @Override + void renameClass(Map<String,String> classnames) { Renamer renamer = new Renamer(info, getConstPool(), classnames); try { renamer.annotationArray(); @@ -312,11 +331,13 @@ public class AnnotationsAttribute extends AttributeInfo { } } - void getRefClasses(Map classnames) { renameClass(classnames); } + @Override + void getRefClasses(Map<String,String> classnames) { renameClass(classnames); } /** * Returns a string representation of this object. */ + @Override public String toString() { Annotation[] a = getAnnotations(); StringBuilder sbuf = new StringBuilder(); @@ -458,7 +479,7 @@ public class AnnotationsAttribute extends AttributeInfo { static class Renamer extends Walker { ConstPool cpool; - Map classnames; + Map<String,String> classnames; /** * Constructs a renamer. It renames some class names @@ -469,17 +490,19 @@ public class AnnotationsAttribute extends AttributeInfo { * @param map pairs of replaced and substituted class names. * It can be null. */ - Renamer(byte[] info, ConstPool cp, Map map) { + Renamer(byte[] info, ConstPool cp, Map<String,String> map) { super(info); cpool = cp; classnames = map; } + @Override int annotation(int pos, int type, int numPairs) throws Exception { renameType(pos - 4, type); return super.annotation(pos, type, numPairs); } + @Override void enumMemberValue(int pos, int typeNameIndex, int constNameIndex) throws Exception { @@ -487,6 +510,7 @@ public class AnnotationsAttribute extends AttributeInfo { super.enumMemberValue(pos, typeNameIndex, constNameIndex); } + @Override void classMemberValue(int pos, int index) throws Exception { renameType(pos + 1, index); super.classMemberValue(pos, index); @@ -506,7 +530,7 @@ public class AnnotationsAttribute extends AttributeInfo { ByteArrayOutputStream output; AnnotationsWriter writer; ConstPool srcPool, destPool; - Map classnames; + Map<String,String> classnames; /** * Constructs a copier. This copier renames some class names @@ -519,11 +543,11 @@ public class AnnotationsAttribute extends AttributeInfo { * @param map pairs of replaced and substituted class names. * It can be null. */ - Copier(byte[] info, ConstPool src, ConstPool dest, Map map) { + Copier(byte[] info, ConstPool src, ConstPool dest, Map<String,String> map) { this(info, src, dest, map, true); } - Copier(byte[] info, ConstPool src, ConstPool dest, Map map, boolean makeWriter) { + Copier(byte[] info, ConstPool src, ConstPool dest, Map<String,String> map, boolean makeWriter) { super(info); output = new ByteArrayOutputStream(); if (makeWriter) @@ -539,31 +563,37 @@ public class AnnotationsAttribute extends AttributeInfo { return output.toByteArray(); } + @Override void parameters(int numParam, int pos) throws Exception { writer.numParameters(numParam); super.parameters(numParam, pos); } + @Override int annotationArray(int pos, int num) throws Exception { writer.numAnnotations(num); return super.annotationArray(pos, num); } + @Override int annotation(int pos, int type, int numPairs) throws Exception { writer.annotation(copyType(type), numPairs); return super.annotation(pos, type, numPairs); } + @Override int memberValuePair(int pos, int nameIndex) throws Exception { writer.memberValuePair(copy(nameIndex)); return super.memberValuePair(pos, nameIndex); } + @Override void constValueMember(int tag, int index) throws Exception { writer.constValueIndex(tag, copy(index)); super.constValueMember(tag, index); } + @Override void enumMemberValue(int pos, int typeNameIndex, int constNameIndex) throws Exception { @@ -571,16 +601,19 @@ public class AnnotationsAttribute extends AttributeInfo { super.enumMemberValue(pos, typeNameIndex, constNameIndex); } + @Override void classMemberValue(int pos, int index) throws Exception { writer.classInfoIndex(copyType(index)); super.classMemberValue(pos, index); } + @Override int annotationMemberValue(int pos) throws Exception { writer.annotationValue(); return super.annotationMemberValue(pos); } + @Override int arrayMemberValue(int pos, int num) throws Exception { writer.arrayValue(num); return super.arrayMemberValue(pos, num); @@ -650,6 +683,7 @@ public class AnnotationsAttribute extends AttributeInfo { return currentMember; } + @Override void parameters(int numParam, int pos) throws Exception { Annotation[][] params = new Annotation[numParam][]; for (int i = 0; i < numParam; ++i) { @@ -660,6 +694,7 @@ public class AnnotationsAttribute extends AttributeInfo { allParams = params; } + @Override int annotationArray(int pos, int num) throws Exception { Annotation[] array = new Annotation[num]; for (int i = 0; i < num; ++i) { @@ -671,17 +706,20 @@ public class AnnotationsAttribute extends AttributeInfo { return pos; } + @Override int annotation(int pos, int type, int numPairs) throws Exception { currentAnno = new Annotation(type, pool); return super.annotation(pos, type, numPairs); } + @Override int memberValuePair(int pos, int nameIndex) throws Exception { pos = super.memberValuePair(pos, nameIndex); currentAnno.addMemberValue(nameIndex, currentMember); return pos; } + @Override void constValueMember(int tag, int index) throws Exception { MemberValue m; ConstPool cp = pool; @@ -721,6 +759,7 @@ public class AnnotationsAttribute extends AttributeInfo { super.constValueMember(tag, index); } + @Override void enumMemberValue(int pos, int typeNameIndex, int constNameIndex) throws Exception { @@ -729,11 +768,13 @@ public class AnnotationsAttribute extends AttributeInfo { super.enumMemberValue(pos, typeNameIndex, constNameIndex); } + @Override void classMemberValue(int pos, int index) throws Exception { currentMember = new ClassMemberValue(index, pool); super.classMemberValue(pos, index); } + @Override int annotationMemberValue(int pos) throws Exception { Annotation anno = currentAnno; pos = super.annotationMemberValue(pos); @@ -742,6 +783,7 @@ public class AnnotationsAttribute extends AttributeInfo { return pos; } + @Override int arrayMemberValue(int pos, int num) throws Exception { ArrayMemberValue amv = new ArrayMemberValue(pool); MemberValue[] elements = new MemberValue[num]; diff --git a/src/main/javassist/bytecode/AttributeInfo.java b/src/main/javassist/bytecode/AttributeInfo.java index 5fd73281..4bfd0dbb 100644 --- a/src/main/javassist/bytecode/AttributeInfo.java +++ b/src/main/javassist/bytecode/AttributeInfo.java @@ -19,11 +19,10 @@ package javassist.bytecode; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; -import java.util.Map; import java.util.ArrayList; -import java.util.ListIterator; +import java.util.Arrays; import java.util.List; -import java.util.Iterator; +import java.util.Map; // Note: if you define a new subclass of AttributeInfo, then // update AttributeInfo.read(), .copy(), and (maybe) write(). @@ -79,65 +78,58 @@ public class AttributeInfo { int name = in.readUnsignedShort(); String nameStr = cp.getUtf8Info(name); char first = nameStr.charAt(0); - if (first < 'M') { - if (first < 'E') { - if (nameStr.equals(AnnotationDefaultAttribute.tag)) - return new AnnotationDefaultAttribute(cp, name, in); - else if (nameStr.equals(BootstrapMethodsAttribute.tag)) - return new BootstrapMethodsAttribute(cp, name, in); - else if (nameStr.equals(CodeAttribute.tag)) - return new CodeAttribute(cp, name, in); - else if (nameStr.equals(ConstantAttribute.tag)) - return new ConstantAttribute(cp, name, in); - else if (nameStr.equals(DeprecatedAttribute.tag)) - return new DeprecatedAttribute(cp, name, in); - } - else { - if (nameStr.equals(EnclosingMethodAttribute.tag)) - return new EnclosingMethodAttribute(cp, name, in); - else if (nameStr.equals(ExceptionsAttribute.tag)) - return new ExceptionsAttribute(cp, name, in); - else if (nameStr.equals(InnerClassesAttribute.tag)) - return new InnerClassesAttribute(cp, name, in); - else if (nameStr.equals(LineNumberAttribute.tag)) - return new LineNumberAttribute(cp, name, in); - else if (nameStr.equals(LocalVariableAttribute.tag)) - return new LocalVariableAttribute(cp, name, in); - else if (nameStr.equals(LocalVariableTypeAttribute.tag)) - return new LocalVariableTypeAttribute(cp, name, in); - } - } - else { - if (first < 'S') { - /* Note that the names of Annotations attributes begin with 'R'. - */ - if (nameStr.equals(MethodParametersAttribute.tag)) - return new MethodParametersAttribute(cp, name, in); - else if (nameStr.equals(AnnotationsAttribute.visibleTag) - || nameStr.equals(AnnotationsAttribute.invisibleTag)) { - // RuntimeVisibleAnnotations or RuntimeInvisibleAnnotations - return new AnnotationsAttribute(cp, name, in); - } - else if (nameStr.equals(ParameterAnnotationsAttribute.visibleTag) - || nameStr.equals(ParameterAnnotationsAttribute.invisibleTag)) - return new ParameterAnnotationsAttribute(cp, name, in); - else if (nameStr.equals(TypeAnnotationsAttribute.visibleTag) - || nameStr.equals(TypeAnnotationsAttribute.invisibleTag)) - return new TypeAnnotationsAttribute(cp, name, in); - } - else { - if (nameStr.equals(SignatureAttribute.tag)) - return new SignatureAttribute(cp, name, in); - else if (nameStr.equals(SourceFileAttribute.tag)) - return new SourceFileAttribute(cp, name, in); - else if (nameStr.equals(SyntheticAttribute.tag)) - return new SyntheticAttribute(cp, name, in); - else if (nameStr.equals(StackMap.tag)) - return new StackMap(cp, name, in); - else if (nameStr.equals(StackMapTable.tag)) - return new StackMapTable(cp, name, in); - } - } + if (first < 'E') + if (nameStr.equals(AnnotationDefaultAttribute.tag)) + return new AnnotationDefaultAttribute(cp, name, in); + else if (nameStr.equals(BootstrapMethodsAttribute.tag)) + return new BootstrapMethodsAttribute(cp, name, in); + else if (nameStr.equals(CodeAttribute.tag)) + return new CodeAttribute(cp, name, in); + else if (nameStr.equals(ConstantAttribute.tag)) + return new ConstantAttribute(cp, name, in); + else if (nameStr.equals(DeprecatedAttribute.tag)) + return new DeprecatedAttribute(cp, name, in); + + if (first < 'M') + if (nameStr.equals(EnclosingMethodAttribute.tag)) + return new EnclosingMethodAttribute(cp, name, in); + else if (nameStr.equals(ExceptionsAttribute.tag)) + return new ExceptionsAttribute(cp, name, in); + else if (nameStr.equals(InnerClassesAttribute.tag)) + return new InnerClassesAttribute(cp, name, in); + else if (nameStr.equals(LineNumberAttribute.tag)) + return new LineNumberAttribute(cp, name, in); + else if (nameStr.equals(LocalVariableAttribute.tag)) + return new LocalVariableAttribute(cp, name, in); + else if (nameStr.equals(LocalVariableTypeAttribute.tag)) + return new LocalVariableTypeAttribute(cp, name, in); + + if (first < 'S') + /* Note that the names of Annotations attributes begin with 'R'. */ + if (nameStr.equals(MethodParametersAttribute.tag)) + return new MethodParametersAttribute(cp, name, in); + else if (nameStr.equals(AnnotationsAttribute.visibleTag) + || nameStr.equals(AnnotationsAttribute.invisibleTag)) + // RuntimeVisibleAnnotations or RuntimeInvisibleAnnotations + return new AnnotationsAttribute(cp, name, in); + else if (nameStr.equals(ParameterAnnotationsAttribute.visibleTag) + || nameStr.equals(ParameterAnnotationsAttribute.invisibleTag)) + return new ParameterAnnotationsAttribute(cp, name, in); + else if (nameStr.equals(TypeAnnotationsAttribute.visibleTag) + || nameStr.equals(TypeAnnotationsAttribute.invisibleTag)) + return new TypeAnnotationsAttribute(cp, name, in); + + if (first >= 'S') + if (nameStr.equals(SignatureAttribute.tag)) + return new SignatureAttribute(cp, name, in); + else if (nameStr.equals(SourceFileAttribute.tag)) + return new SourceFileAttribute(cp, name, in); + else if (nameStr.equals(SyntheticAttribute.tag)) + return new SyntheticAttribute(cp, name, in); + else if (nameStr.equals(StackMap.tag)) + return new StackMap(cp, name, in); + else if (nameStr.equals(StackMapTable.tag)) + return new StackMapTable(cp, name, in); return new AttributeInfo(cp, name, in); } @@ -189,88 +181,68 @@ public class AttributeInfo { * @param classnames pairs of replaced and substituted * class names. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { - int s = info.length; - byte[] srcInfo = info; - byte[] newInfo = new byte[s]; - for (int i = 0; i < s; ++i) - newInfo[i] = srcInfo[i]; - - return new AttributeInfo(newCp, getName(), newInfo); + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) + { + return new AttributeInfo(newCp, getName(), Arrays.copyOf(info, info.length)); } - void write(DataOutputStream out) throws IOException { + void write(DataOutputStream out) throws IOException + { out.writeShort(name); out.writeInt(info.length); if (info.length > 0) out.write(info); } - static int getLength(ArrayList list) { + static int getLength(List<AttributeInfo> attributes) { int size = 0; - int n = list.size(); - for (int i = 0; i < n; ++i) { - AttributeInfo attr = (AttributeInfo)list.get(i); + + for (AttributeInfo attr:attributes) size += attr.length(); - } return size; } - static AttributeInfo lookup(ArrayList list, String name) { - if (list == null) + static AttributeInfo lookup(List<AttributeInfo> attributes, String name) { + if (attributes == null) return null; - ListIterator iterator = list.listIterator(); - while (iterator.hasNext()) { - AttributeInfo ai = (AttributeInfo)iterator.next(); + for (AttributeInfo ai:attributes) if (ai.getName().equals(name)) return ai; - } return null; // no such attribute } - static synchronized AttributeInfo remove(ArrayList list, String name) { - if (list == null) + static synchronized AttributeInfo remove(List<AttributeInfo> attributes, String name) { + if (attributes == null) return null; - AttributeInfo removed = null; - ListIterator iterator = list.listIterator(); - while (iterator.hasNext()) { - AttributeInfo ai = (AttributeInfo)iterator.next(); - if (ai.getName().equals(name)) { - iterator.remove(); - removed = ai; - } - } - - return removed; + for (AttributeInfo ai:attributes) + if (ai.getName().equals(name)) + if (attributes.remove(ai)) + return ai; + + return null; } - static void writeAll(ArrayList list, DataOutputStream out) + static void writeAll(List<AttributeInfo> attributes, DataOutputStream out) throws IOException { - if (list == null) + if (attributes == null) return; - int n = list.size(); - for (int i = 0; i < n; ++i) { - AttributeInfo attr = (AttributeInfo)list.get(i); + for (AttributeInfo attr:attributes) attr.write(out); - } } - static ArrayList copyAll(ArrayList list, ConstPool cp) { - if (list == null) + static List<AttributeInfo> copyAll(List<AttributeInfo> attributes, ConstPool cp) { + if (attributes == null) return null; - ArrayList newList = new ArrayList(); - int n = list.size(); - for (int i = 0; i < n; ++i) { - AttributeInfo attr = (AttributeInfo)list.get(i); + List<AttributeInfo> newList = new ArrayList<AttributeInfo>(); + for (AttributeInfo attr:attributes) newList.add(attr.copy(cp, null)); - } return newList; } @@ -282,31 +254,31 @@ public class AttributeInfo { * override these methods. */ void renameClass(String oldname, String newname) {} - void renameClass(Map classnames) {} + void renameClass(Map<String,String> classnames) {} - static void renameClass(List attributes, String oldname, String newname) { - Iterator iterator = attributes.iterator(); - while (iterator.hasNext()) { - AttributeInfo ai = (AttributeInfo)iterator.next(); + static void renameClass(List<AttributeInfo> attributes, String oldname, String newname) { + if (attributes == null) + return; + + for (AttributeInfo ai:attributes) ai.renameClass(oldname, newname); - } } - static void renameClass(List attributes, Map classnames) { - Iterator iterator = attributes.iterator(); - while (iterator.hasNext()) { - AttributeInfo ai = (AttributeInfo)iterator.next(); + static void renameClass(List<AttributeInfo> attributes, Map<String,String> classnames) { + if (attributes == null) + return; + + for (AttributeInfo ai:attributes) ai.renameClass(classnames); - } } - void getRefClasses(Map classnames) {} + void getRefClasses(Map<String,String> classnames) {} + + static void getRefClasses(List<AttributeInfo> attributes, Map<String,String> classnames) { + if (attributes == null) + return; - static void getRefClasses(List attributes, Map classnames) { - Iterator iterator = attributes.iterator(); - while (iterator.hasNext()) { - AttributeInfo ai = (AttributeInfo)iterator.next(); + for (AttributeInfo ai:attributes) ai.getRefClasses(classnames); - } } } diff --git a/src/main/javassist/bytecode/BadBytecode.java b/src/main/javassist/bytecode/BadBytecode.java index 9959ae6c..7a049b45 100644 --- a/src/main/javassist/bytecode/BadBytecode.java +++ b/src/main/javassist/bytecode/BadBytecode.java @@ -20,6 +20,9 @@ package javassist.bytecode; * Signals that a bad bytecode sequence has been found. */ public class BadBytecode extends Exception { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public BadBytecode(int opcode) { super("bytecode " + opcode); } diff --git a/src/main/javassist/bytecode/BootstrapMethodsAttribute.java b/src/main/javassist/bytecode/BootstrapMethodsAttribute.java index 98268b87..94a0481f 100644 --- a/src/main/javassist/bytecode/BootstrapMethodsAttribute.java +++ b/src/main/javassist/bytecode/BootstrapMethodsAttribute.java @@ -108,7 +108,8 @@ public class BootstrapMethodsAttribute extends AttributeInfo { * @param classnames pairs of replaced and substituted * class names. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { BootstrapMethod[] methods = getMethods(); ConstPool thisCp = getConstPool(); for (int i = 0; i < methods.length; i++) { diff --git a/src/main/javassist/bytecode/ByteStream.java b/src/main/javassist/bytecode/ByteStream.java index 29302f30..ee485911 100644 --- a/src/main/javassist/bytecode/ByteStream.java +++ b/src/main/javassist/bytecode/ByteStream.java @@ -16,8 +16,8 @@ package javassist.bytecode; -import java.io.OutputStream; import java.io.IOException; +import java.io.OutputStream; final class ByteStream extends OutputStream { private byte[] buf; @@ -38,16 +38,19 @@ final class ByteStream extends OutputStream { count += len; } + @Override public void write(byte[] data) { write(data, 0, data.length); } + @Override public void write(byte[] data, int off, int len) { enlarge(len); System.arraycopy(data, off, buf, count, len); count += len; } + @Override public void write(int b) { enlarge(1); int oldCount = count; diff --git a/src/main/javassist/bytecode/Bytecode.java b/src/main/javassist/bytecode/Bytecode.java index 34068f8d..37a6d127 100644 --- a/src/main/javassist/bytecode/Bytecode.java +++ b/src/main/javassist/bytecode/Bytecode.java @@ -28,6 +28,7 @@ class ByteVector implements Cloneable { size = 0; } + @Override public Object clone() throws CloneNotSupportedException { ByteVector bv = (ByteVector)super.clone(); bv.buffer = (byte[])buffer.clone(); @@ -164,6 +165,7 @@ public class Bytecode extends ByteVector implements Cloneable, Opcode { * The constant pool object is shared between this object * and the cloned object. */ + @Override public Object clone() { try { Bytecode bc = (Bytecode)super.clone(); @@ -325,6 +327,7 @@ public class Bytecode extends ByteVector implements Cloneable, Opcode { * * @throws ArrayIndexOutOfBoundsException if offset is invalid. */ + @Override public int read(int offset) { return super.read(offset); } @@ -355,6 +358,7 @@ public class Bytecode extends ByteVector implements Cloneable, Opcode { * * @throws ArrayIndexOutOfBoundsException if offset is invalid. */ + @Override public void write(int offset, int value) { super.write(offset, value); } @@ -380,6 +384,7 @@ public class Bytecode extends ByteVector implements Cloneable, Opcode { /** * Appends an 8bit value to the end of the bytecode sequence. */ + @Override public void add(int code) { super.add(code); } @@ -396,6 +401,7 @@ public class Bytecode extends ByteVector implements Cloneable, Opcode { * * @param length the gap length in byte. */ + @Override public void addGap(int length) { super.addGap(length); } diff --git a/src/main/javassist/bytecode/ClassFile.java b/src/main/javassist/bytecode/ClassFile.java index 1a404cff..880c18b8 100644 --- a/src/main/javassist/bytecode/ClassFile.java +++ b/src/main/javassist/bytecode/ClassFile.java @@ -62,9 +62,9 @@ public final class ClassFile { int accessFlags; int superClass; int[] interfaces; - ArrayList fields; - ArrayList methods; - ArrayList attributes; + List<FieldInfo> fields; + List<MethodInfo> methods; + List<AttributeInfo> attributes; String thisclassname; // not JVM-internal name String[] cachedInterfaces; String cachedSuperclass; @@ -186,11 +186,11 @@ public final class ClassFile { initSuperclass(superclass); interfaces = null; - fields = new ArrayList(); - methods = new ArrayList(); + fields = new ArrayList<FieldInfo>(); + methods = new ArrayList<MethodInfo>(); thisclassname = classname; - attributes = new ArrayList(); + attributes = new ArrayList<AttributeInfo>(); attributes.add(new SourceFileAttribute(constPool, getSourcefileName(thisclassname))); } @@ -207,11 +207,7 @@ public final class ClassFile { } private static String getSourcefileName(String qname) { - int index = qname.lastIndexOf('.'); - if (index >= 0) - qname = qname.substring(index + 1); - - return qname + ".java"; + return qname.replaceAll("^.*\\.","") + ".java"; } /** @@ -221,19 +217,11 @@ public final class ClassFile { */ public void compact() { ConstPool cp = compact0(); - ArrayList list = methods; - int n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + for (MethodInfo minfo:methods) minfo.compact(cp); - } - list = fields; - n = list.size(); - for (int i = 0; i < n; ++i) { - FieldInfo finfo = (FieldInfo)list.get(i); + for (FieldInfo finfo:fields) finfo.compact(cp); - } attributes = AttributeInfo.copyAll(attributes, cp); constPool = cp; @@ -246,12 +234,10 @@ public final class ClassFile { if (sc != null) superClass = cp.addClassInfo(getSuperclass()); - if (interfaces != null) { - int n = interfaces.length; - for (int i = 0; i < n; ++i) + if (interfaces != null) + for (int i = 0; i < interfaces.length; ++i) interfaces[i] = cp.addClassInfo(constPool.getClassInfo(interfaces[i])); - } return cp; } @@ -264,7 +250,7 @@ public final class ClassFile { */ public void prune() { ConstPool cp = compact0(); - ArrayList newAttributes = new ArrayList(); + List<AttributeInfo> newAttributes = new ArrayList<AttributeInfo>(); AttributeInfo invisibleAnnotations = getAttribute(AnnotationsAttribute.invisibleTag); if (invisibleAnnotations != null) { @@ -279,26 +265,18 @@ public final class ClassFile { newAttributes.add(visibleAnnotations); } - AttributeInfo signature + AttributeInfo signature = getAttribute(SignatureAttribute.tag); if (signature != null) { signature = signature.copy(cp, null); newAttributes.add(signature); } - - ArrayList list = methods; - int n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + + for (MethodInfo minfo:methods) minfo.prune(cp); - } - list = fields; - n = list.size(); - for (int i = 0; i < n; ++i) { - FieldInfo finfo = (FieldInfo)list.get(i); + for (FieldInfo finfo:fields) finfo.prune(cp); - } attributes = newAttributes; constPool = cp; @@ -423,12 +401,8 @@ public final class ClassFile { try { this.superClass = constPool.addClassInfo(superclass); - ArrayList list = methods; - int n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + for (MethodInfo minfo:methods) minfo.setSuperclass(superclass); - } } catch (BadBytecode e) { throw new CannotCompileException(e); @@ -451,9 +425,6 @@ public final class ClassFile { * the substituted class name */ public final void renameClass(String oldname, String newname) { - ArrayList list; - int n; - if (oldname.equals(newname)) return; @@ -465,19 +436,13 @@ public final class ClassFile { constPool.renameClass(oldname, newname); AttributeInfo.renameClass(attributes, oldname, newname); - list = methods; - n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + for (MethodInfo minfo :methods) { String desc = minfo.getDescriptor(); minfo.setDescriptor(Descriptor.rename(desc, oldname, newname)); AttributeInfo.renameClass(minfo.getAttributes(), oldname, newname); } - list = fields; - n = list.size(); - for (int i = 0; i < n; ++i) { - FieldInfo finfo = (FieldInfo)list.get(i); + for (FieldInfo finfo:fields) { String desc = finfo.getDescriptor(); finfo.setDescriptor(Descriptor.rename(desc, oldname, newname)); AttributeInfo.renameClass(finfo.getAttributes(), oldname, newname); @@ -493,8 +458,8 @@ public final class ClassFile { * representation like <code>java/lang/Object</code>. * @see #renameClass(String,String) */ - public final void renameClass(Map classnames) { - String jvmNewThisName = (String)classnames.get(Descriptor + public final void renameClass(Map<String,String> classnames) { + String jvmNewThisName = classnames.get(Descriptor .toJvmName(thisclassname)); if (jvmNewThisName != null) thisclassname = Descriptor.toJavaName(jvmNewThisName); @@ -502,19 +467,13 @@ public final class ClassFile { constPool.renameClass(classnames); AttributeInfo.renameClass(attributes, classnames); - ArrayList list = methods; - int n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + for (MethodInfo minfo:methods) { String desc = minfo.getDescriptor(); minfo.setDescriptor(Descriptor.rename(desc, classnames)); AttributeInfo.renameClass(minfo.getAttributes(), classnames); } - list = fields; - n = list.size(); - for (int i = 0; i < n; ++i) { - FieldInfo finfo = (FieldInfo)list.get(i); + for (FieldInfo finfo:fields) { String desc = finfo.getDescriptor(); finfo.setDescriptor(Descriptor.rename(desc, classnames)); AttributeInfo.renameClass(finfo.getAttributes(), classnames); @@ -525,23 +484,17 @@ public final class ClassFile { * Internal-use only. * <code>CtClass.getRefClasses()</code> calls this method. */ - public final void getRefClasses(Map classnames) { + public final void getRefClasses(Map<String,String> classnames) { constPool.renameClass(classnames); AttributeInfo.getRefClasses(attributes, classnames); - ArrayList list = methods; - int n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + for (MethodInfo minfo:methods) { String desc = minfo.getDescriptor(); Descriptor.rename(desc, classnames); AttributeInfo.getRefClasses(minfo.getAttributes(), classnames); } - list = fields; - n = list.size(); - for (int i = 0; i < n; ++i) { - FieldInfo finfo = (FieldInfo)list.get(i); + for (FieldInfo finfo:fields) { String desc = finfo.getDescriptor(); Descriptor.rename(desc, classnames); AttributeInfo.getRefClasses(finfo.getAttributes(), classnames); @@ -560,9 +513,8 @@ public final class ClassFile { if (interfaces == null) rtn = new String[0]; else { - int n = interfaces.length; - String[] list = new String[n]; - for (int i = 0; i < n; ++i) + String[] list = new String[interfaces.length]; + for (int i = 0; i < interfaces.length; ++i) list[i] = constPool.getClassInfo(interfaces[i]); rtn = list; @@ -581,9 +533,8 @@ public final class ClassFile { public void setInterfaces(String[] nameList) { cachedInterfaces = null; if (nameList != null) { - int n = nameList.length; - interfaces = new int[n]; - for (int i = 0; i < n; ++i) + interfaces = new int[nameList.length]; + for (int i = 0; i < nameList.length; ++i) interfaces[i] = constPool.addClassInfo(nameList[i]); } } @@ -613,7 +564,7 @@ public final class ClassFile { * @return a list of <code>FieldInfo</code>. * @see FieldInfo */ - public List getFields() { + public List<FieldInfo> getFields() { return fields; } @@ -641,12 +592,9 @@ public final class ClassFile { private void testExistingField(String name, String descriptor) throws DuplicateMemberException { - ListIterator it = fields.listIterator(0); - while (it.hasNext()) { - FieldInfo minfo = (FieldInfo)it.next(); + for (FieldInfo minfo:fields) if (minfo.getName().equals(name)) throw new DuplicateMemberException("duplicate field: " + name); - } } /** @@ -655,7 +603,7 @@ public final class ClassFile { * @return a list of <code>MethodInfo</code>. * @see MethodInfo */ - public List getMethods() { + public List<MethodInfo> getMethods() { return methods; } @@ -666,14 +614,9 @@ public final class ClassFile { * @return null if no such method is found. */ public MethodInfo getMethod(String name) { - ArrayList list = methods; - int n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + for (MethodInfo minfo:methods) if (minfo.getName().equals(name)) return minfo; - } - return null; } @@ -714,16 +657,16 @@ public final class ClassFile { { String name = newMinfo.getName(); String descriptor = newMinfo.getDescriptor(); - ListIterator it = methods.listIterator(0); + ListIterator<MethodInfo> it = methods.listIterator(0); while (it.hasNext()) - if (isDuplicated(newMinfo, name, descriptor, (MethodInfo)it.next(), it)) + if (isDuplicated(newMinfo, name, descriptor, it.next(), it)) throw new DuplicateMemberException("duplicate method: " + name + " in " + this.getName()); } private static boolean isDuplicated(MethodInfo newMethod, String newName, String newDesc, MethodInfo minfo, - ListIterator it) + ListIterator<MethodInfo> it) { if (!minfo.getName().equals(newName)) return false; @@ -735,14 +678,11 @@ public final class ClassFile { if (desc.equals(newDesc)) { if (notBridgeMethod(minfo)) return true; - else { // if the bridge method with the same signature // already exists, replace it. - it.remove(); - return false; - } + it.remove(); + return false; } - else return false; // return notBridgeMethod(minfo) && notBridgeMethod(newMethod); } @@ -763,7 +703,7 @@ public final class ClassFile { * @return a list of <code>AttributeInfo</code> objects. * @see AttributeInfo */ - public List getAttributes() { + public List<AttributeInfo> getAttributes() { return attributes; } @@ -776,19 +716,14 @@ public final class ClassFile { * {@link AnnotationsAttribute#visibleTag} or * {@link AnnotationsAttribute#invisibleTag}. * </p> - * + * * @param name attribute name * @see #getAttributes() */ public AttributeInfo getAttribute(String name) { - ArrayList list = attributes; - int n = list.size(); - for (int i = 0; i < n; ++i) { - AttributeInfo ai = (AttributeInfo)list.get(i); + for (AttributeInfo ai:attributes) if (ai.getName().equals(name)) return ai; - } - return null; } @@ -824,8 +759,7 @@ public final class ClassFile { = (SourceFileAttribute)getAttribute(SourceFileAttribute.tag); if (sf == null) return null; - else - return sf.getFileName(); + return sf.getFileName(); } private void read(DataInputStream in) throws IOException { @@ -852,16 +786,16 @@ public final class ClassFile { ConstPool cp = constPool; n = in.readUnsignedShort(); - fields = new ArrayList(); + fields = new ArrayList<FieldInfo>(); for (i = 0; i < n; ++i) addField2(new FieldInfo(cp, in)); n = in.readUnsignedShort(); - methods = new ArrayList(); + methods = new ArrayList<MethodInfo>(); for (i = 0; i < n; ++i) addMethod2(new MethodInfo(cp, in)); - attributes = new ArrayList(); + attributes = new ArrayList<AttributeInfo>(); n = in.readUnsignedShort(); for (i = 0; i < n; ++i) addAttribute(AttributeInfo.read(cp, in)); @@ -892,21 +826,16 @@ public final class ClassFile { for (i = 0; i < n; ++i) out.writeShort(interfaces[i]); - ArrayList list = fields; - n = list.size(); + n = fields.size(); out.writeShort(n); for (i = 0; i < n; ++i) { - FieldInfo finfo = (FieldInfo)list.get(i); + FieldInfo finfo = fields.get(i); finfo.write(out); } - list = methods; - n = list.size(); - out.writeShort(n); - for (i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + out.writeShort(methods.size()); + for (MethodInfo minfo:methods) minfo.write(out); - } out.writeShort(attributes.size()); AttributeInfo.writeAll(attributes, out); diff --git a/src/main/javassist/bytecode/ClassFilePrinter.java b/src/main/javassist/bytecode/ClassFilePrinter.java index 388ab517..a9c7d9ba 100644 --- a/src/main/javassist/bytecode/ClassFilePrinter.java +++ b/src/main/javassist/bytecode/ClassFilePrinter.java @@ -17,9 +17,10 @@ package javassist.bytecode; import java.io.PrintWriter; -import javassist.Modifier; import java.util.List; +import javassist.Modifier; + /** * A utility class for priting the contents of a class file. * It prints a constant pool table, fields, and methods in a @@ -37,9 +38,6 @@ public class ClassFilePrinter { * Prints the contents of a class file. */ public static void print(ClassFile cf, PrintWriter out) { - List list; - int n; - /* 0x0020 (SYNCHRONIZED) means ACC_SUPER if the modifiers * are of a class. */ @@ -62,10 +60,8 @@ public class ClassFilePrinter { } out.println(); - list = cf.getFields(); - n = list.size(); - for (int i = 0; i < n; ++i) { - FieldInfo finfo = (FieldInfo)list.get(i); + List<FieldInfo> fields = cf.getFields(); + for (FieldInfo finfo:fields) { int acc = finfo.getAccessFlags(); out.println(Modifier.toString(AccessFlag.toModifier(acc)) + " " + finfo.getName() + "\t" @@ -74,10 +70,8 @@ public class ClassFilePrinter { } out.println(); - list = cf.getMethods(); - n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + List<MethodInfo> methods = cf.getMethods(); + for (MethodInfo minfo:methods) { int acc = minfo.getAccessFlags(); out.println(Modifier.toString(AccessFlag.toModifier(acc)) + " " + minfo.getName() + "\t" @@ -90,13 +84,11 @@ public class ClassFilePrinter { printAttributes(cf.getAttributes(), out, 'c'); } - static void printAttributes(List list, PrintWriter out, char kind) { + static void printAttributes(List<AttributeInfo> list, PrintWriter out, char kind) { if (list == null) return; - int n = list.size(); - for (int i = 0; i < n; ++i) { - AttributeInfo ai = (AttributeInfo)list.get(i); + for (AttributeInfo ai:list) { if (ai instanceof CodeAttribute) { CodeAttribute ca = (CodeAttribute)ai; out.println("attribute: " + ai.getName() + ": " diff --git a/src/main/javassist/bytecode/ClassFileWriter.java b/src/main/javassist/bytecode/ClassFileWriter.java index d1e76ce0..931ffcb4 100644 --- a/src/main/javassist/bytecode/ClassFileWriter.java +++ b/src/main/javassist/bytecode/ClassFileWriter.java @@ -16,10 +16,9 @@ package javassist.bytecode; -import java.io.OutputStream; import java.io.DataOutputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.OutputStream; /** * A quick class-file writer. This is useful when a generated diff --git a/src/main/javassist/bytecode/CodeAttribute.java b/src/main/javassist/bytecode/CodeAttribute.java index 090ae74d..4c8ea2f2 100644 --- a/src/main/javassist/bytecode/CodeAttribute.java +++ b/src/main/javassist/bytecode/CodeAttribute.java @@ -19,9 +19,8 @@ package javassist.bytecode; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; -import java.util.List; import java.util.ArrayList; -import java.util.Iterator; +import java.util.List; import java.util.Map; /** @@ -45,7 +44,7 @@ public class CodeAttribute extends AttributeInfo implements Opcode { private int maxStack; private int maxLocals; private ExceptionTable exceptions; - private ArrayList attributes; + private List<AttributeInfo> attributes; /** * Constructs a <code>Code_attribute</code>. @@ -64,7 +63,7 @@ public class CodeAttribute extends AttributeInfo implements Opcode { maxLocals = locals; info = code; exceptions = etable; - attributes = new ArrayList(); + attributes = new ArrayList<AttributeInfo>(); } /** @@ -76,7 +75,7 @@ public class CodeAttribute extends AttributeInfo implements Opcode { * @param classnames pairs of replaced and substituted * class names. */ - private CodeAttribute(ConstPool cp, CodeAttribute src, Map classnames) + private CodeAttribute(ConstPool cp, CodeAttribute src, Map<String,String> classnames) throws BadBytecode { super(cp, tag); @@ -84,11 +83,11 @@ public class CodeAttribute extends AttributeInfo implements Opcode { maxStack = src.getMaxStack(); maxLocals = src.getMaxLocals(); exceptions = src.getExceptionTable().copy(cp, classnames); - attributes = new ArrayList(); - List src_attr = src.getAttributes(); + attributes = new ArrayList<AttributeInfo>(); + List<AttributeInfo> src_attr = src.getAttributes(); int num = src_attr.size(); for (int i = 0; i < num; ++i) { - AttributeInfo ai = (AttributeInfo)src_attr.get(i); + AttributeInfo ai = src_attr.get(i); attributes.add(ai.copy(cp, classnames)); } @@ -99,6 +98,7 @@ public class CodeAttribute extends AttributeInfo implements Opcode { throws IOException { super(cp, name_id, (byte[])null); + @SuppressWarnings("unused") int attr_len = in.readInt(); maxStack = in.readUnsignedShort(); @@ -110,7 +110,7 @@ public class CodeAttribute extends AttributeInfo implements Opcode { exceptions = new ExceptionTable(cp, in); - attributes = new ArrayList(); + attributes = new ArrayList<AttributeInfo>(); int num = in.readUnsignedShort(); for (int i = 0; i < num; ++i) attributes.add(AttributeInfo.read(cp, in)); @@ -130,7 +130,8 @@ public class CodeAttribute extends AttributeInfo implements Opcode { * * @return <code>CodeAttribute</code> object. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) throws RuntimeCopyException { try { @@ -146,6 +147,9 @@ public class CodeAttribute extends AttributeInfo implements Opcode { * in <code>CodeAttribute</code>. */ public static class RuntimeCopyException extends RuntimeException { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + /** * Constructs an exception. */ @@ -159,11 +163,13 @@ public class CodeAttribute extends AttributeInfo implements Opcode { * structure. * The returned value is <code>attribute_length + 6</code>. */ + @Override public int length() { return 18 + info.length + exceptions.size() * 8 + AttributeInfo.getLength(attributes); } + @Override void write(DataOutputStream out) throws IOException { out.writeShort(name); // attribute_name_index out.writeInt(length() - 6); // attribute_length @@ -181,7 +187,8 @@ public class CodeAttribute extends AttributeInfo implements Opcode { * * @throws java.lang.UnsupportedOperationException always thrown. */ - public byte[] get() { + @Override + public byte[] get() { throw new UnsupportedOperationException("CodeAttribute.get()"); } @@ -190,19 +197,23 @@ public class CodeAttribute extends AttributeInfo implements Opcode { * * @throws java.lang.UnsupportedOperationException always thrown. */ + @Override public void set(byte[] newinfo) { throw new UnsupportedOperationException("CodeAttribute.set()"); } + @Override void renameClass(String oldname, String newname) { AttributeInfo.renameClass(attributes, oldname, newname); } - void renameClass(Map classnames) { + @Override + void renameClass(Map<String,String> classnames) { AttributeInfo.renameClass(attributes, classnames); } - void getRefClasses(Map classnames) { + @Override + void getRefClasses(Map<String,String> classnames) { AttributeInfo.getRefClasses(attributes, classnames); } @@ -294,7 +305,7 @@ public class CodeAttribute extends AttributeInfo implements Opcode { * * @see AttributeInfo */ - public List getAttributes() { return attributes; } + public List<AttributeInfo> getAttributes() { return attributes; } /** * Returns the attribute with the specified name. @@ -339,7 +350,7 @@ public class CodeAttribute extends AttributeInfo implements Opcode { /** * Copies code. */ - private byte[] copyCode(ConstPool destCp, Map classnames, + private byte[] copyCode(ConstPool destCp, Map<String,String> classnames, ExceptionTable etable, CodeAttribute destCa) throws BadBytecode { @@ -353,7 +364,7 @@ public class CodeAttribute extends AttributeInfo implements Opcode { private static LdcEntry copyCode(byte[] code, int beginPos, int endPos, ConstPool srcCp, byte[] newcode, - ConstPool destCp, Map classnameMap) + ConstPool destCp, Map<String,String> classnameMap) throws BadBytecode { int i2, index; @@ -425,7 +436,7 @@ public class CodeAttribute extends AttributeInfo implements Opcode { private static void copyConstPoolInfo(int i, byte[] code, ConstPool srcCp, byte[] newcode, ConstPool destCp, - Map classnameMap) { + Map<String,String> classnameMap) { int index = ((code[i] & 0xff) << 8) | (code[i + 1] & 0xff); index = srcCp.copy(index, destCp, classnameMap); newcode[i] = (byte)(index >> 8); diff --git a/src/main/javassist/bytecode/CodeIterator.java b/src/main/javassist/bytecode/CodeIterator.java index e1edcbb7..b9a23c2c 100644 --- a/src/main/javassist/bytecode/CodeIterator.java +++ b/src/main/javassist/bytecode/CodeIterator.java @@ -17,6 +17,7 @@ package javassist.bytecode; import java.util.ArrayList; +import java.util.List; /** * An iterator for editing a code attribute. @@ -305,8 +306,8 @@ public class CodeIterator implements Opcode { String cname = cp.getMethodrefClassName(mref); if (cname.equals(thisClassName) == (skipThis > 0)) return index; - else - break; + + break; } } } @@ -772,19 +773,15 @@ public class CodeIterator implements Opcode { return index + 6; else return index + 4; // WIDE ... - else { - int index2 = (index & ~3) + 8; - if (opcode == LOOKUPSWITCH) { - int npairs = ByteArray.read32bit(code, index2); - return index2 + npairs * 8 + 4; - } - else if (opcode == TABLESWITCH) { - int low = ByteArray.read32bit(code, index2); - int high = ByteArray.read32bit(code, index2 + 4); - return index2 + (high - low + 1) * 4 + 8; - } - // else - // throw new BadBytecode(opcode); + int index2 = (index & ~3) + 8; + if (opcode == LOOKUPSWITCH) { + int npairs = ByteArray.read32bit(code, index2); + return index2 + npairs * 8 + 4; + } + else if (opcode == TABLESWITCH) { + int low = ByteArray.read32bit(code, index2); + int high = ByteArray.read32bit(code, index2 + 4); + return index2 + (high - low + 1) * 4 + 8; } } catch (IndexOutOfBoundsException e) { @@ -796,7 +793,10 @@ public class CodeIterator implements Opcode { // methods for implementing insertGap(). - static class AlignmentException extends Exception {} + static class AlignmentException extends Exception { + + /** default serialVersionUID */ + private static final long serialVersionUID = 1L;} /** * insertGapCore0() inserts a gap (some NOPs). @@ -1075,7 +1075,7 @@ public class CodeIterator implements Opcode { throws BadBytecode { Pointers pointers = new Pointers(0, 0, 0, etable, ca); - ArrayList jumps = makeJumpList(code, code.length, pointers); + List<Branch> jumps = makeJumpList(code, code.length, pointers); while (ldcs != null) { addLdcW(ldcs, jumps); ldcs = ldcs.next; @@ -1085,12 +1085,12 @@ public class CodeIterator implements Opcode { return r; } - private static void addLdcW(CodeAttribute.LdcEntry ldcs, ArrayList jumps) { + private static void addLdcW(CodeAttribute.LdcEntry ldcs, List<Branch> jumps) { int where = ldcs.where; LdcW ldcw = new LdcW(where, ldcs.index); int s = jumps.size(); for (int i = 0; i < s; i++) - if (where < ((Branch)jumps.get(i)).orgPos) { + if (where < jumps.get(i).orgPos) { jumps.add(i, ldcw); return; } @@ -1119,7 +1119,7 @@ public class CodeIterator implements Opcode { return code; Pointers pointers = new Pointers(currentPos, mark, where, etable, ca); - ArrayList jumps = makeJumpList(code, code.length, pointers); + List<Branch> jumps = makeJumpList(code, code.length, pointers); byte[] r = insertGap2w(code, where, gapLength, exclusive, jumps, pointers); currentPos = pointers.cursor; mark = pointers.mark; @@ -1136,42 +1136,39 @@ public class CodeIterator implements Opcode { } private static byte[] insertGap2w(byte[] code, int where, int gapLength, - boolean exclusive, ArrayList jumps, Pointers ptrs) + boolean exclusive, List<Branch> jumps, Pointers ptrs) throws BadBytecode { - int n = jumps.size(); if (gapLength > 0) { ptrs.shiftPc(where, gapLength, exclusive); - for (int i = 0; i < n; i++) - ((Branch)jumps.get(i)).shift(where, gapLength, exclusive); + for (Branch b:jumps) + b.shift(where, gapLength, exclusive); } boolean unstable = true; do { while (unstable) { unstable = false; - for (int i = 0; i < n; i++) { - Branch b = (Branch)jumps.get(i); + for (Branch b:jumps) { if (b.expanded()) { unstable = true; int p = b.pos; int delta = b.deltaSize(); ptrs.shiftPc(p, delta, false); - for (int j = 0; j < n; j++) - ((Branch)jumps.get(j)).shift(p, delta, false); + for (Branch bb:jumps) + bb.shift(p, delta, false); } } } - for (int i = 0; i < n; i++) { - Branch b = (Branch)jumps.get(i); + for (Branch b:jumps) { int diff = b.gapChanged(); if (diff > 0) { unstable = true; int p = b.pos; ptrs.shiftPc(p, diff, false); - for (int j = 0; j < n; j++) - ((Branch)jumps.get(j)).shift(p, diff, false); + for (Branch bb:jumps) + bb.shift(p, diff, false); } } } while (unstable); @@ -1179,10 +1176,10 @@ public class CodeIterator implements Opcode { return makeExapndedCode(code, jumps, where, gapLength); } - private static ArrayList makeJumpList(byte[] code, int endPos, Pointers ptrs) + private static List<Branch> makeJumpList(byte[] code, int endPos, Pointers ptrs) throws BadBytecode { - ArrayList jumps = new ArrayList(); + List<Branch> jumps = new ArrayList<Branch>(); int nextPos; for (int i = 0; i < endPos; i = nextPos) { nextPos = nextOpcode(code, i); @@ -1240,16 +1237,14 @@ public class CodeIterator implements Opcode { return jumps; } - private static byte[] makeExapndedCode(byte[] code, ArrayList jumps, + private static byte[] makeExapndedCode(byte[] code, List<Branch> jumps, int where, int gapLength) throws BadBytecode { int n = jumps.size(); int size = code.length + gapLength; - for (int i = 0; i < n; i++) { - Branch b = (Branch)jumps.get(i); + for (Branch b:jumps) size += b.deltaSize(); - } byte[] newcode = new byte[size]; int src = 0, dest = 0, bindex = 0; @@ -1257,12 +1252,12 @@ public class CodeIterator implements Opcode { Branch b; int bpos; if (0 < n) { - b = (Branch)jumps.get(0); + b = jumps.get(0); bpos = b.orgPos; } else { b = null; - bpos = len; // src will be never equal to bpos + bpos = len; // src will be never equal to bpos } while (src < len) { @@ -1279,7 +1274,7 @@ public class CodeIterator implements Opcode { src += s; dest += s + b.deltaSize(); if (++bindex < n) { - b = (Branch)jumps.get(bindex); + b = jumps.get(bindex); bpos = b.orgPos; } else { @@ -1341,17 +1336,19 @@ public class CodeIterator implements Opcode { state = true; } + @Override boolean expanded() { if (state) { state = false; return true; } - else - return false; + return false; } + @Override int deltaSize() { return 1; } + @Override int write(int srcPos, byte[] code, int destPos, byte[] newcode) { newcode[destPos] = LDC_W; ByteArray.write16bit(index, newcode, destPos + 1); @@ -1372,6 +1369,7 @@ public class CodeIterator implements Opcode { state = BIT16; } + @Override void shift(int where, int gapLength, boolean exclusive) { offset = shiftOffset(pos, offset, where, gapLength, exclusive); super.shift(where, gapLength, exclusive); @@ -1380,18 +1378,20 @@ public class CodeIterator implements Opcode { state = EXPAND; } + @Override boolean expanded() { if (state == EXPAND) { state = BIT32; return true; } - else - return false; + return false; } + @Override abstract int deltaSize(); abstract void write32(int src, byte[] code, int dest, byte[] newcode); + @Override int write(int src, byte[] code, int dest, byte[] newcode) { if (state == BIT32) write32(src, code, dest, newcode); @@ -1410,10 +1410,12 @@ public class CodeIterator implements Opcode { super(p, off); } + @Override int deltaSize() { return state == BIT32 ? 2 : 0; } + @Override void write32(int src, byte[] code, int dest, byte[] newcode) { newcode[dest] = (byte)(((code[src] & 0xff) == GOTO) ? GOTO_W : JSR_W); ByteArray.write32bit(offset, newcode, dest + 1); @@ -1426,10 +1428,12 @@ public class CodeIterator implements Opcode { super(p, off); } + @Override int deltaSize() { return state == BIT32 ? 5 : 0; } + @Override void write32(int src, byte[] code, int dest, byte[] newcode) { newcode[dest] = (byte)opcode(code[src] & 0xff); newcode[dest + 1] = 0; @@ -1443,12 +1447,9 @@ public class CodeIterator implements Opcode { return IFNONNULL; else if (op == IFNONNULL) return IFNULL; - else { - if (((op - IFEQ) & 1) == 0) - return op + 1; - else - return op - 1; - } + if (((op - IFEQ) & 1) == 0) + return op + 1; + return op - 1; } } @@ -1460,11 +1461,13 @@ public class CodeIterator implements Opcode { offset = off; } + @Override void shift(int where, int gapLength, boolean exclusive) { offset = shiftOffset(pos, offset, where, gapLength, exclusive); super.shift(where, gapLength, exclusive); } + @Override int write(int src, byte[] code, int dest, byte[] newcode) { newcode[dest] = code[src]; ByteArray.write32bit(offset, newcode, dest + 1); @@ -1485,6 +1488,7 @@ public class CodeIterator implements Opcode { this.pointers = ptrs; } + @Override void shift(int where, int gapLength, boolean exclusive) { int p = pos; defaultByte = shiftOffset(p, defaultByte, where, gapLength, exclusive); @@ -1495,6 +1499,7 @@ public class CodeIterator implements Opcode { super.shift(where, gapLength, exclusive); } + @Override int gapChanged() { int newGap = 3 - (pos & 3); if (newGap > gap) { @@ -1506,10 +1511,12 @@ public class CodeIterator implements Opcode { return 0; } + @Override int deltaSize() { return gap - (3 - (orgPos & 3)); } + @Override int write(int src, byte[] code, int dest, byte[] newcode) throws BadBytecode { int padding = 3 - (pos & 3); int nops = gap - padding; @@ -1562,6 +1569,7 @@ public class CodeIterator implements Opcode { this.high = high; } + @Override int write2(int dest, byte[] newcode) { ByteArray.write32bit(low, newcode, dest); ByteArray.write32bit(high, newcode, dest + 4); @@ -1575,6 +1583,7 @@ public class CodeIterator implements Opcode { return 8 + 4 * n; } + @Override int tableSize() { return 8 + 4 * offsets.length; } } @@ -1586,6 +1595,7 @@ public class CodeIterator implements Opcode { this.matches = matches; } + @Override int write2(int dest, byte[] newcode) { int n = matches.length; ByteArray.write32bit(n, newcode, dest); @@ -1599,6 +1609,7 @@ public class CodeIterator implements Opcode { return 4 + 8 * n; } + @Override int tableSize() { return 4 + 8 * matches.length; } } } diff --git a/src/main/javassist/bytecode/ConstPool.java b/src/main/javassist/bytecode/ConstPool.java index 2ac31ba2..0447ece7 100644 --- a/src/main/javassist/bytecode/ConstPool.java +++ b/src/main/javassist/bytecode/ConstPool.java @@ -16,11 +16,11 @@ package javassist.bytecode; +import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.PrintWriter; import java.io.IOException; +import java.io.PrintWriter; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -31,11 +31,12 @@ import javassist.CtClass; /** * Constant pool table. */ -public final class ConstPool { +public final class ConstPool +{ LongVector items; int numOfItems; int thisClassInfo; - HashMap itemsCache; + Map<ConstInfo,ConstInfo> itemsCache; /** * <code>CONSTANT_Class</code> @@ -174,7 +175,8 @@ public final class ConstPool { * @param thisclass the name of the class using this constant * pool table */ - public ConstPool(String thisclass) { + public ConstPool(String thisclass) + { items = new LongVector(); itemsCache = null; numOfItems = 0; @@ -187,7 +189,8 @@ public final class ConstPool { * * @param in byte stream. */ - public ConstPool(DataInputStream in) throws IOException { + public ConstPool(DataInputStream in) throws IOException + { itemsCache = null; thisClassInfo = 0; /* read() initializes items and numOfItems, and do addItem(null). @@ -195,21 +198,24 @@ public final class ConstPool { read(in); } - void prune() { + void prune() + { itemsCache = null; } /** * Returns the number of entries in this table. */ - public int getSize() { + public int getSize() + { return numOfItems; } /** * Returns the name of the class using this constant pool table. */ - public String getClassName() { + public String getClassName() + { return getClassInfo(thisClassInfo); } @@ -217,15 +223,18 @@ public final class ConstPool { * Returns the index of <code>CONSTANT_Class_info</code> structure * specifying the class using this constant pool table. */ - public int getThisClassInfo() { + public int getThisClassInfo() + { return thisClassInfo; } - void setThisClassInfo(int i) { + void setThisClassInfo(int i) + { thisClassInfo = i; } - ConstInfo getItem(int n) { + ConstInfo getItem(int n) + { return items.elementAt(n); } @@ -236,7 +245,8 @@ public final class ConstPool { * @return either <code>CONST_Class</code>, <code>CONST_Fieldref</code>, * <code>CONST_Methodref</code>, or ... */ - public int getTag(int index) { + public int getTag(int index) + { return getItem(index).getTag(); } @@ -251,12 +261,12 @@ public final class ConstPool { * are not slashes but dots). * @see javassist.ClassPool#getCtClass(String) */ - public String getClassInfo(int index) { + public String getClassInfo(int index) + { ClassInfo c = (ClassInfo)getItem(index); if (c == null) return null; - else - return Descriptor.toJavaName(getUtf8Info(c.name)); + return Descriptor.toJavaName(getUtf8Info(c.name)); } /** @@ -268,17 +278,15 @@ public final class ConstPool { * @see javassist.ClassPool#getCtClass(String) * @since 3.15 */ - public String getClassInfoByDescriptor(int index) { + public String getClassInfoByDescriptor(int index) + { ClassInfo c = (ClassInfo)getItem(index); if (c == null) return null; - else { - String className = getUtf8Info(c.name); - if (className.charAt(0) == '[') - return className; - else - return Descriptor.of(className); - } + String className = getUtf8Info(c.name); + if (className.charAt(0) == '[') + return className; + return Descriptor.of(className); } /** @@ -286,7 +294,8 @@ public final class ConstPool { * <code>CONSTANT_NameAndType_info</code> structure * at the given index. */ - public int getNameAndTypeName(int index) { + public int getNameAndTypeName(int index) + { NameAndTypeInfo ntinfo = (NameAndTypeInfo)getItem(index); return ntinfo.memberName; } @@ -296,7 +305,8 @@ public final class ConstPool { * <code>CONSTANT_NameAndType_info</code> structure * at the given index. */ - public int getNameAndTypeDescriptor(int index) { + public int getNameAndTypeDescriptor(int index) + { NameAndTypeInfo ntinfo = (NameAndTypeInfo)getItem(index); return ntinfo.typeDescriptor; } @@ -310,7 +320,8 @@ public final class ConstPool { * * @since 3.6 */ - public int getMemberClass(int index) { + public int getMemberClass(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); return minfo.classIndex; } @@ -324,7 +335,8 @@ public final class ConstPool { * * @since 3.6 */ - public int getMemberNameAndType(int index) { + public int getMemberNameAndType(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); return minfo.nameAndTypeIndex; } @@ -334,7 +346,8 @@ public final class ConstPool { * <code>CONSTANT_Fieldref_info</code> structure * at the given index. */ - public int getFieldrefClass(int index) { + public int getFieldrefClass(int index) + { FieldrefInfo finfo = (FieldrefInfo)getItem(index); return finfo.classIndex; } @@ -346,12 +359,12 @@ public final class ConstPool { * * @return the name of the class at that <code>class_index</code>. */ - public String getFieldrefClassName(int index) { + public String getFieldrefClassName(int index) + { FieldrefInfo f = (FieldrefInfo)getItem(index); if (f == null) return null; - else - return getClassInfo(f.classIndex); + return getClassInfo(f.classIndex); } /** @@ -359,7 +372,8 @@ public final class ConstPool { * <code>CONSTANT_Fieldref_info</code> structure * at the given index. */ - public int getFieldrefNameAndType(int index) { + public int getFieldrefNameAndType(int index) + { FieldrefInfo finfo = (FieldrefInfo)getItem(index); return finfo.nameAndTypeIndex; } @@ -372,17 +386,15 @@ public final class ConstPool { * @param index an index to a <code>CONSTANT_Fieldref_info</code>. * @return the name of the field. */ - public String getFieldrefName(int index) { + public String getFieldrefName(int index) + { FieldrefInfo f = (FieldrefInfo)getItem(index); if (f == null) return null; - else { - NameAndTypeInfo n = (NameAndTypeInfo)getItem(f.nameAndTypeIndex); - if(n == null) - return null; - else - return getUtf8Info(n.memberName); - } + NameAndTypeInfo n = (NameAndTypeInfo)getItem(f.nameAndTypeIndex); + if(n == null) + return null; + return getUtf8Info(n.memberName); } /** @@ -393,17 +405,15 @@ public final class ConstPool { * @param index an index to a <code>CONSTANT_Fieldref_info</code>. * @return the type descriptor of the field. */ - public String getFieldrefType(int index) { + public String getFieldrefType(int index) + { FieldrefInfo f = (FieldrefInfo)getItem(index); if (f == null) return null; - else { - NameAndTypeInfo n = (NameAndTypeInfo)getItem(f.nameAndTypeIndex); - if(n == null) - return null; - else - return getUtf8Info(n.typeDescriptor); - } + NameAndTypeInfo n = (NameAndTypeInfo)getItem(f.nameAndTypeIndex); + if(n == null) + return null; + return getUtf8Info(n.typeDescriptor); } /** @@ -411,7 +421,8 @@ public final class ConstPool { * <code>CONSTANT_Methodref_info</code> structure * at the given index. */ - public int getMethodrefClass(int index) { + public int getMethodrefClass(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); return minfo.classIndex; } @@ -423,12 +434,12 @@ public final class ConstPool { * * @return the name of the class at that <code>class_index</code>. */ - public String getMethodrefClassName(int index) { + public String getMethodrefClassName(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); if (minfo == null) return null; - else - return getClassInfo(minfo.classIndex); + return getClassInfo(minfo.classIndex); } /** @@ -436,7 +447,8 @@ public final class ConstPool { * <code>CONSTANT_Methodref_info</code> structure * at the given index. */ - public int getMethodrefNameAndType(int index) { + public int getMethodrefNameAndType(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); return minfo.nameAndTypeIndex; } @@ -449,18 +461,16 @@ public final class ConstPool { * @param index an index to a <code>CONSTANT_Methodref_info</code>. * @return the name of the method. */ - public String getMethodrefName(int index) { + public String getMethodrefName(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); if (minfo == null) return null; - else { - NameAndTypeInfo n - = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); - if(n == null) - return null; - else - return getUtf8Info(n.memberName); - } + NameAndTypeInfo n + = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); + if(n == null) + return null; + return getUtf8Info(n.memberName); } /** @@ -471,18 +481,16 @@ public final class ConstPool { * @param index an index to a <code>CONSTANT_Methodref_info</code>. * @return the descriptor of the method. */ - public String getMethodrefType(int index) { + public String getMethodrefType(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); if (minfo == null) return null; - else { - NameAndTypeInfo n - = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); - if(n == null) - return null; - else - return getUtf8Info(n.typeDescriptor); - } + NameAndTypeInfo n + = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); + if(n == null) + return null; + return getUtf8Info(n.typeDescriptor); } /** @@ -490,7 +498,8 @@ public final class ConstPool { * <code>CONSTANT_InterfaceMethodref_info</code> structure * at the given index. */ - public int getInterfaceMethodrefClass(int index) { + public int getInterfaceMethodrefClass(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); return minfo.classIndex; } @@ -502,7 +511,8 @@ public final class ConstPool { * * @return the name of the class at that <code>class_index</code>. */ - public String getInterfaceMethodrefClassName(int index) { + public String getInterfaceMethodrefClassName(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); return getClassInfo(minfo.classIndex); } @@ -512,7 +522,8 @@ public final class ConstPool { * <code>CONSTANT_InterfaceMethodref_info</code> structure * at the given index. */ - public int getInterfaceMethodrefNameAndType(int index) { + public int getInterfaceMethodrefNameAndType(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); return minfo.nameAndTypeIndex; } @@ -526,18 +537,16 @@ public final class ConstPool { * a <code>CONSTANT_InterfaceMethodref_info</code>. * @return the name of the method. */ - public String getInterfaceMethodrefName(int index) { + public String getInterfaceMethodrefName(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); if (minfo == null) return null; - else { - NameAndTypeInfo n - = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); - if(n == null) - return null; - else - return getUtf8Info(n.memberName); - } + NameAndTypeInfo n + = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); + if(n == null) + return null; + return getUtf8Info(n.memberName); } /** @@ -549,18 +558,16 @@ public final class ConstPool { * a <code>CONSTANT_InterfaceMethodref_info</code>. * @return the descriptor of the method. */ - public String getInterfaceMethodrefType(int index) { + public String getInterfaceMethodrefType(int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); if (minfo == null) return null; - else { - NameAndTypeInfo n - = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); - if(n == null) - return null; - else - return getUtf8Info(n.typeDescriptor); - } + NameAndTypeInfo n + = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); + if(n == null) + return null; + return getUtf8Info(n.typeDescriptor); } /** * Reads <code>CONSTANT_Integer_info</code>, <code>_Float_info</code>, @@ -571,7 +578,8 @@ public final class ConstPool { * @return a <code>String</code> value or a wrapped primitive-type * value. */ - public Object getLdcValue(int index) { + public Object getLdcValue(int index) + { ConstInfo constInfo = this.getItem(index); Object value = null; if (constInfo instanceof StringInfo) @@ -584,8 +592,6 @@ public final class ConstPool { value = Long.valueOf(getLongInfo(index)); else if (constInfo instanceof DoubleInfo) value = Double.valueOf(getDoubleInfo(index)); - else - value = null; return value; } @@ -596,7 +602,8 @@ public final class ConstPool { * * @return the value specified by this entry. */ - public int getIntegerInfo(int index) { + public int getIntegerInfo(int index) + { IntegerInfo i = (IntegerInfo)getItem(index); return i.value; } @@ -607,7 +614,8 @@ public final class ConstPool { * * @return the value specified by this entry. */ - public float getFloatInfo(int index) { + public float getFloatInfo(int index) + { FloatInfo i = (FloatInfo)getItem(index); return i.value; } @@ -618,7 +626,8 @@ public final class ConstPool { * * @return the value specified by this entry. */ - public long getLongInfo(int index) { + public long getLongInfo(int index) + { LongInfo i = (LongInfo)getItem(index); return i.value; } @@ -629,7 +638,8 @@ public final class ConstPool { * * @return the value specified by this entry. */ - public double getDoubleInfo(int index) { + public double getDoubleInfo(int index) + { DoubleInfo i = (DoubleInfo)getItem(index); return i.value; } @@ -640,7 +650,8 @@ public final class ConstPool { * * @return the string specified by <code>string_index</code>. */ - public String getStringInfo(int index) { + public String getStringInfo(int index) + { StringInfo si = (StringInfo)getItem(index); return getUtf8Info(si.string); } @@ -651,7 +662,8 @@ public final class ConstPool { * * @return the string specified by this entry. */ - public String getUtf8Info(int index) { + public String getUtf8Info(int index) + { Utf8Info utf = (Utf8Info)getItem(index); return utf.string; } @@ -672,7 +684,8 @@ public final class ConstPool { * @see #REF_putStatic * @since 3.17 */ - public int getMethodHandleKind(int index) { + public int getMethodHandleKind(int index) + { MethodHandleInfo mhinfo = (MethodHandleInfo)getItem(index); return mhinfo.refKind; } @@ -684,7 +697,8 @@ public final class ConstPool { * * @since 3.17 */ - public int getMethodHandleIndex(int index) { + public int getMethodHandleIndex(int index) + { MethodHandleInfo mhinfo = (MethodHandleInfo)getItem(index); return mhinfo.refIndex; } @@ -696,7 +710,8 @@ public final class ConstPool { * * @since 3.17 */ - public int getMethodTypeInfo(int index) { + public int getMethodTypeInfo(int index) + { MethodTypeInfo mtinfo = (MethodTypeInfo)getItem(index); return mtinfo.descriptor; } @@ -708,7 +723,8 @@ public final class ConstPool { * * @since 3.17 */ - public int getInvokeDynamicBootstrap(int index) { + public int getInvokeDynamicBootstrap(int index) + { InvokeDynamicInfo iv = (InvokeDynamicInfo)getItem(index); return iv.bootstrap; } @@ -720,7 +736,8 @@ public final class ConstPool { * * @since 3.17 */ - public int getInvokeDynamicNameAndType(int index) { + public int getInvokeDynamicNameAndType(int index) + { InvokeDynamicInfo iv = (InvokeDynamicInfo)getItem(index); return iv.nameAndType; } @@ -734,17 +751,15 @@ public final class ConstPool { * @return the descriptor of the method. * @since 3.17 */ - public String getInvokeDynamicType(int index) { + public String getInvokeDynamicType(int index) + { InvokeDynamicInfo iv = (InvokeDynamicInfo)getItem(index); if (iv == null) return null; - else { - NameAndTypeInfo n = (NameAndTypeInfo)getItem(iv.nameAndType); - if(n == null) - return null; - else - return getUtf8Info(n.typeDescriptor); - } + NameAndTypeInfo n = (NameAndTypeInfo)getItem(iv.nameAndType); + if(n == null) + return null; + return getUtf8Info(n.typeDescriptor); } /** @@ -754,7 +769,8 @@ public final class ConstPool { * @return the module name at <code>name_index</code>. * @since 3.22 */ - public String getModuleInfo(int index) { + public String getModuleInfo(int index) + { ModuleInfo mi = (ModuleInfo)getItem(index); return getUtf8Info(mi.name); } @@ -763,11 +779,12 @@ public final class ConstPool { * Reads the <code>name_index</code> field of the * <code>CONSTANT_Package_info</code> structure at the given index. * - * @return the package name at <code>name_index</code>. It is a slash-separated name - * such as com/oracle/net. + * @return the package name at <code>name_index</code>. It is a slash- + * separated name such as com/oracle/net. * @since 3.22 */ - public String getPackageInfo(int index) { + public String getPackageInfo(int index) + { PackageInfo mi = (PackageInfo)getItem(index); return getUtf8Info(mi.name); } @@ -782,7 +799,8 @@ public final class ConstPool { * If it is not that constructor, * <code>isConstructor()</code> returns 0. */ - public int isConstructor(String classname, int index) { + public int isConstructor(String classname, int index) + { return isMember(classname, MethodInfo.nameInit, index); } @@ -802,7 +820,8 @@ public final class ConstPool { * If it is not that member, * <code>isMember()</code> returns 0. */ - public int isMember(String classname, String membername, int index) { + public int isMember(String classname, String membername, int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); if (getClassInfo(minfo.classIndex).equals(classname)) { NameAndTypeInfo ntinfo @@ -831,34 +850,34 @@ public final class ConstPool { * Otherwise, null if that structure does not * match the given member name and descriptor. */ - public String eqMember(String membername, String desc, int index) { + public String eqMember(String membername, String desc, int index) + { MemberrefInfo minfo = (MemberrefInfo)getItem(index); NameAndTypeInfo ntinfo = (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex); if (getUtf8Info(ntinfo.memberName).equals(membername) && getUtf8Info(ntinfo.typeDescriptor).equals(desc)) return getClassInfo(minfo.classIndex); - else - return null; // false + return null; // false } - private int addItem0(ConstInfo info) { + private int addItem0(ConstInfo info) + { items.addElement(info); return numOfItems++; } - private int addItem(ConstInfo info) { + private int addItem(ConstInfo info) + { if (itemsCache == null) itemsCache = makeItemsCache(items); - ConstInfo found = (ConstInfo)itemsCache.get(info); + ConstInfo found = itemsCache.get(info); if (found != null) return found.index; - else { - items.addElement(info); - itemsCache.put(info, info); - return numOfItems++; - } + items.addElement(info); + itemsCache.put(info, info); + return numOfItems++; } /** @@ -872,7 +891,8 @@ public final class ConstPool { * @param classnames the map or null. * @return the index of the copied item into the destination ClassPool. */ - public int copy(int n, ConstPool dest, Map classnames) { + public int copy(int n, ConstPool dest, Map<String,String> classnames) + { if (n == 0) return 0; @@ -892,7 +912,8 @@ public final class ConstPool { * * @return the index of the added entry. */ - public int addClassInfo(CtClass c) { + public int addClassInfo(CtClass c) + { if (c == THIS) return thisClassInfo; else if (!c.isArray()) @@ -917,7 +938,8 @@ public final class ConstPool { * (or the JVM-internal representation of that name). * @return the index of the added entry. */ - public int addClassInfo(String qname) { + public int addClassInfo(String qname) + { int utf8 = addUtf8Info(Descriptor.toJvmName(qname)); return addItem(new ClassInfo(utf8, numOfItems)); } @@ -931,7 +953,8 @@ public final class ConstPool { * @param type <code>descriptor_index</code> * @return the index of the added entry. */ - public int addNameAndTypeInfo(String name, String type) { + public int addNameAndTypeInfo(String name, String type) + { return addNameAndTypeInfo(addUtf8Info(name), addUtf8Info(type)); } @@ -942,7 +965,8 @@ public final class ConstPool { * @param type <code>descriptor_index</code> * @return the index of the added entry. */ - public int addNameAndTypeInfo(int name, int type) { + public int addNameAndTypeInfo(int name, int type) + { return addItem(new NameAndTypeInfo(name, type, numOfItems)); } @@ -959,7 +983,8 @@ public final class ConstPool { * of <code>CONSTANT_NameAndType_info</code>. * @return the index of the added entry. */ - public int addFieldrefInfo(int classInfo, String name, String type) { + public int addFieldrefInfo(int classInfo, String name, String type) + { int nt = addNameAndTypeInfo(name, type); return addFieldrefInfo(classInfo, nt); } @@ -971,8 +996,10 @@ public final class ConstPool { * @param nameAndTypeInfo <code>name_and_type_index</code>. * @return the index of the added entry. */ - public int addFieldrefInfo(int classInfo, int nameAndTypeInfo) { - return addItem(new FieldrefInfo(classInfo, nameAndTypeInfo, numOfItems)); + public int addFieldrefInfo(int classInfo, int nameAndTypeInfo) + { + return addItem(new FieldrefInfo(classInfo, nameAndTypeInfo, + numOfItems)); } /** @@ -988,7 +1015,8 @@ public final class ConstPool { * of <code>CONSTANT_NameAndType_info</code>. * @return the index of the added entry. */ - public int addMethodrefInfo(int classInfo, String name, String type) { + public int addMethodrefInfo(int classInfo, String name, String type) + { int nt = addNameAndTypeInfo(name, type); return addMethodrefInfo(classInfo, nt); } @@ -1000,8 +1028,10 @@ public final class ConstPool { * @param nameAndTypeInfo <code>name_and_type_index</code>. * @return the index of the added entry. */ - public int addMethodrefInfo(int classInfo, int nameAndTypeInfo) { - return addItem(new MethodrefInfo(classInfo, nameAndTypeInfo, numOfItems)); + public int addMethodrefInfo(int classInfo, int nameAndTypeInfo) + { + return addItem(new MethodrefInfo(classInfo, + nameAndTypeInfo, numOfItems)); } /** @@ -1018,8 +1048,10 @@ public final class ConstPool { * of <code>CONSTANT_NameAndType_info</code>. * @return the index of the added entry. */ - public int addInterfaceMethodrefInfo(int classInfo, String name, - String type) { + public int addInterfaceMethodrefInfo(int classInfo, + String name, + String type) + { int nt = addNameAndTypeInfo(name, type); return addInterfaceMethodrefInfo(classInfo, nt); } @@ -1033,8 +1065,10 @@ public final class ConstPool { * @return the index of the added entry. */ public int addInterfaceMethodrefInfo(int classInfo, - int nameAndTypeInfo) { - return addItem(new InterfaceMethodrefInfo(classInfo, nameAndTypeInfo, + int nameAndTypeInfo) + { + return addItem(new InterfaceMethodrefInfo(classInfo, + nameAndTypeInfo, numOfItems)); } @@ -1047,7 +1081,8 @@ public final class ConstPool { * * @return the index of the added entry. */ - public int addStringInfo(String str) { + public int addStringInfo(String str) + { int utf = addUtf8Info(str); return addItem(new StringInfo(utf, numOfItems)); } @@ -1058,7 +1093,8 @@ public final class ConstPool { * * @return the index of the added entry. */ - public int addIntegerInfo(int i) { + public int addIntegerInfo(int i) + { return addItem(new IntegerInfo(i, numOfItems)); } @@ -1068,7 +1104,8 @@ public final class ConstPool { * * @return the index of the added entry. */ - public int addFloatInfo(float f) { + public int addFloatInfo(float f) + { return addItem(new FloatInfo(f, numOfItems)); } @@ -1078,7 +1115,8 @@ public final class ConstPool { * * @return the index of the added entry. */ - public int addLongInfo(long l) { + public int addLongInfo(long l) + { int i = addItem(new LongInfo(l, numOfItems)); if (i == numOfItems - 1) // if not existing addConstInfoPadding(); @@ -1092,7 +1130,8 @@ public final class ConstPool { * * @return the index of the added entry. */ - public int addDoubleInfo(double d) { + public int addDoubleInfo(double d) + { int i = addItem(new DoubleInfo(d, numOfItems)); if (i == numOfItems - 1) // if not existing addConstInfoPadding(); @@ -1106,7 +1145,8 @@ public final class ConstPool { * * @return the index of the added entry. */ - public int addUtf8Info(String utf8) { + public int addUtf8Info(String utf8) + { return addItem(new Utf8Info(utf8, numOfItems)); } @@ -1121,7 +1161,8 @@ public final class ConstPool { * * @since 3.17 */ - public int addMethodHandleInfo(int kind, int index) { + public int addMethodHandleInfo(int kind, int index) + { return addItem(new MethodHandleInfo(kind, index, numOfItems)); } @@ -1134,7 +1175,8 @@ public final class ConstPool { * * @since 3.17 */ - public int addMethodTypeInfo(int desc) { + public int addMethodTypeInfo(int desc) + { return addItem(new MethodTypeInfo(desc, numOfItems)); } @@ -1148,7 +1190,8 @@ public final class ConstPool { * * @since 3.17 */ - public int addInvokeDynamicInfo(int bootstrap, int nameAndType) { + public int addInvokeDynamicInfo(int bootstrap, int nameAndType) + { return addItem(new InvokeDynamicInfo(bootstrap, nameAndType, numOfItems)); } @@ -1158,7 +1201,8 @@ public final class ConstPool { * @return the index of the added entry. * @since 3.22 */ - public int addModuleInfo(int nameIndex) { + public int addModuleInfo(int nameIndex) + { return addItem(new ModuleInfo(nameIndex, numOfItems)); } @@ -1168,7 +1212,8 @@ public final class ConstPool { * @return the index of the added entry. * @since 3.22 */ - public int addPackageInfo(int nameIndex) { + public int addPackageInfo(int nameIndex) + { return addItem(new PackageInfo(nameIndex, numOfItems)); } @@ -1177,8 +1222,9 @@ public final class ConstPool { * * @return a set of class names (<code>String</code> objects). */ - public Set getClassNames() { - HashSet result = new HashSet(); + public Set<String> getClassNames() + { + Set<String> result = new HashSet<String>(); LongVector v = items; int size = numOfItems; for (int i = 1; i < size; ++i) { @@ -1195,7 +1241,8 @@ public final class ConstPool { * @param oldName the replaced name (JVM-internal representation). * @param newName the substituted name (JVM-internal representation). */ - public void renameClass(String oldName, String newName) { + public void renameClass(String oldName, String newName) + { LongVector v = items; int size = numOfItems; for (int i = 1; i < size; ++i) { @@ -1210,7 +1257,8 @@ public final class ConstPool { * @param classnames specifies pairs of replaced and substituted * name. */ - public void renameClass(Map classnames) { + public void renameClass(Map<String,String> classnames) + { LongVector v = items; int size = numOfItems; for (int i = 1; i < size; ++i) { @@ -1219,7 +1267,8 @@ public final class ConstPool { } } - private void read(DataInputStream in) throws IOException { + private void read(DataInputStream in) throws IOException + { int n = in.readUnsignedShort(); items = new LongVector(n); @@ -1235,21 +1284,22 @@ public final class ConstPool { } } - private static HashMap makeItemsCache(LongVector items) { - HashMap cache = new HashMap(); + private static Map<ConstInfo,ConstInfo> makeItemsCache(LongVector items) + { + Map<ConstInfo,ConstInfo> cache = new HashMap<ConstInfo,ConstInfo>(); int i = 1; while (true) { ConstInfo info = items.elementAt(i++); if (info == null) break; - else - cache.put(info, info); + cache.put(info, info); } return cache; } - private int readOne(DataInputStream in) throws IOException { + private int readOne(DataInputStream in) throws IOException + { ConstInfo info; int tag = in.readUnsignedByte(); switch (tag) { @@ -1302,7 +1352,8 @@ public final class ConstPool { info = new PackageInfo(in, numOfItems); break; default : - throw new IOException("invalid constant type: " + tag + " at " + numOfItems); + throw new IOException("invalid constant type: " + + tag + " at " + numOfItems); } addItem0(info); @@ -1312,7 +1363,8 @@ public final class ConstPool { /** * Writes the contents of the constant pool table. */ - public void write(DataOutputStream out) throws IOException { + public void write(DataOutputStream out) throws IOException + { out.writeShort(numOfItems); LongVector v = items; int size = numOfItems; @@ -1323,14 +1375,16 @@ public final class ConstPool { /** * Prints the contents of the constant pool table. */ - public void print() { + public void print() + { print(new PrintWriter(System.out, true)); } /** * Prints the contents of the constant pool table. */ - public void print(PrintWriter out) { + public void print(PrintWriter out) + { int size = numOfItems; for (int i = 1; i < size; ++i) { out.print(i); @@ -1340,7 +1394,8 @@ public final class ConstPool { } } -abstract class ConstInfo { +abstract class ConstInfo +{ int index; public ConstInfo(int i) { index = i; } @@ -1348,14 +1403,18 @@ abstract class ConstInfo { public abstract int getTag(); public String getClassName(ConstPool cp) { return null; } - public void renameClass(ConstPool cp, String oldName, String newName, HashMap cache) {} - public void renameClass(ConstPool cp, Map classnames, HashMap cache) {} - public abstract int copy(ConstPool src, ConstPool dest, Map classnames); - // ** classnames is a mapping between JVM names. + public void renameClass(ConstPool cp, String oldName, String newName, + Map<ConstInfo,ConstInfo> cache) {} + public void renameClass(ConstPool cp, Map<String,String> classnames, + Map<ConstInfo,ConstInfo> cache) {} + public abstract int copy(ConstPool src, ConstPool dest, + Map<String, String> classnames); + // ** classnames is a mapping between JVM names. public abstract void write(DataOutputStream out) throws IOException; public abstract void print(PrintWriter out); + @Override public String toString() { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintWriter out = new PrintWriter(bout); @@ -1366,49 +1425,68 @@ abstract class ConstInfo { /* padding following DoubleInfo or LongInfo. */ -class ConstInfoPadding extends ConstInfo { +class ConstInfoPadding extends ConstInfo +{ public ConstInfoPadding(int i) { super(i); } + @Override public int getTag() { return 0; } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, Map<String,String> map) + { return dest.addConstInfoPadding(); } + @Override public void write(DataOutputStream out) throws IOException {} - public void print(PrintWriter out) { + @Override + public void print(PrintWriter out) + { out.println("padding"); } } -class ClassInfo extends ConstInfo { +class ClassInfo extends ConstInfo +{ static final int tag = 7; int name; - public ClassInfo(int className, int index) { + public ClassInfo(int className, int index) + { super(index); name = className; } - public ClassInfo(DataInputStream in, int index) throws IOException { + public ClassInfo(DataInputStream in, int index) throws IOException + { super(index); name = in.readUnsignedShort(); } + @Override public int hashCode() { return name; } - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) + { return obj instanceof ClassInfo && ((ClassInfo)obj).name == name; } + @Override public int getTag() { return tag; } - public String getClassName(ConstPool cp) { + @Override + public String getClassName(ConstPool cp) + { return cp.getUtf8Info(name); } - public void renameClass(ConstPool cp, String oldName, String newName, HashMap cache) { + @Override + public void renameClass(ConstPool cp, String oldName, String newName, + Map<ConstInfo,ConstInfo> cache) + { String nameStr = cp.getUtf8Info(name); String newNameStr = null; if (nameStr.equals(oldName)) @@ -1429,7 +1507,10 @@ class ClassInfo extends ConstInfo { } } - public void renameClass(ConstPool cp, Map map, HashMap cache) { + @Override + public void renameClass(ConstPool cp, Map<String,String> map, + Map<ConstInfo,ConstInfo> cache) + { String oldName = cp.getUtf8Info(name); String newName = null; if (oldName.charAt(0) == '[') { @@ -1438,7 +1519,7 @@ class ClassInfo extends ConstInfo { newName = s; } else { - String s = (String)map.get(oldName); + String s = map.get(oldName); if (s != null && !s.equals(oldName)) newName = s; } @@ -1454,10 +1535,12 @@ class ClassInfo extends ConstInfo { } } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, Map<String,String> map) + { String classname = src.getUtf8Info(name); if (map != null) { - String newname = (String)map.get(classname); + String newname = map.get(classname); if (newname != null) classname = newname; } @@ -1465,48 +1548,62 @@ class ClassInfo extends ConstInfo { return dest.addClassInfo(classname); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(tag); out.writeShort(name); } - public void print(PrintWriter out) { + @Override + public void print(PrintWriter out) + { out.print("Class #"); out.println(name); } } -class NameAndTypeInfo extends ConstInfo { +class NameAndTypeInfo extends ConstInfo +{ static final int tag = 12; int memberName; int typeDescriptor; - public NameAndTypeInfo(int name, int type, int index) { + public NameAndTypeInfo(int name, int type, int index) + { super(index); memberName = name; typeDescriptor = type; } - public NameAndTypeInfo(DataInputStream in, int index) throws IOException { + public NameAndTypeInfo(DataInputStream in, int index) throws IOException + { super(index); memberName = in.readUnsignedShort(); typeDescriptor = in.readUnsignedShort(); } + @Override public int hashCode() { return (memberName << 16) ^ typeDescriptor; } - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) + { if (obj instanceof NameAndTypeInfo) { NameAndTypeInfo nti = (NameAndTypeInfo)obj; - return nti.memberName == memberName && nti.typeDescriptor == typeDescriptor; + return nti.memberName == memberName + && nti.typeDescriptor == typeDescriptor; } - else - return false; + return false; } + @Override public int getTag() { return tag; } - public void renameClass(ConstPool cp, String oldName, String newName, HashMap cache) { + @Override + public void renameClass(ConstPool cp, String oldName, String newName, + Map<ConstInfo,ConstInfo> cache) + { String type = cp.getUtf8Info(typeDescriptor); String type2 = Descriptor.rename(type, oldName, newName); if (type != type2) @@ -1519,7 +1616,10 @@ class NameAndTypeInfo extends ConstInfo { } } - public void renameClass(ConstPool cp, Map map, HashMap cache) { + @Override + public void renameClass(ConstPool cp, Map<String,String> map, + Map<ConstInfo,ConstInfo> cache) + { String type = cp.getUtf8Info(typeDescriptor); String type2 = Descriptor.rename(type, map); if (type != type2) @@ -1532,7 +1632,9 @@ class NameAndTypeInfo extends ConstInfo { } } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, Map<String,String> map) + { String mname = src.getUtf8Info(memberName); String tdesc = src.getUtf8Info(typeDescriptor); tdesc = Descriptor.rename(tdesc, map); @@ -1540,12 +1642,14 @@ class NameAndTypeInfo extends ConstInfo { dest.addUtf8Info(tdesc)); } + @Override public void write(DataOutputStream out) throws IOException { out.writeByte(tag); out.writeShort(memberName); out.writeShort(typeDescriptor); } + @Override public void print(PrintWriter out) { out.print("NameAndType #"); out.print(memberName); @@ -1554,35 +1658,43 @@ class NameAndTypeInfo extends ConstInfo { } } -abstract class MemberrefInfo extends ConstInfo { +abstract class MemberrefInfo extends ConstInfo +{ int classIndex; int nameAndTypeIndex; - public MemberrefInfo(int cindex, int ntindex, int thisIndex) { + public MemberrefInfo(int cindex, int ntindex, int thisIndex) + { super(thisIndex); classIndex = cindex; nameAndTypeIndex = ntindex; } - public MemberrefInfo(DataInputStream in, int thisIndex) throws IOException { + public MemberrefInfo(DataInputStream in, int thisIndex) + throws IOException + { super(thisIndex); classIndex = in.readUnsignedShort(); nameAndTypeIndex = in.readUnsignedShort(); } + @Override public int hashCode() { return (classIndex << 16) ^ nameAndTypeIndex; } + @Override public boolean equals(Object obj) { if (obj instanceof MemberrefInfo) { MemberrefInfo mri = (MemberrefInfo)obj; - return mri.classIndex == classIndex && mri.nameAndTypeIndex == nameAndTypeIndex - && mri.getClass() == this.getClass(); + return mri.classIndex == classIndex + && mri.nameAndTypeIndex == nameAndTypeIndex + && mri.getClass() == this.getClass(); } - else - return false; + return false; } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, Map<String,String> map) + { int classIndex2 = src.getItem(classIndex).copy(src, dest, map); int ntIndex2 = src.getItem(nameAndTypeIndex).copy(src, dest, map); return copy2(dest, classIndex2, ntIndex2); @@ -1590,13 +1702,17 @@ abstract class MemberrefInfo extends ConstInfo { abstract protected int copy2(ConstPool dest, int cindex, int ntindex); - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(getTag()); out.writeShort(classIndex); out.writeShort(nameAndTypeIndex); } - public void print(PrintWriter out) { + @Override + public void print(PrintWriter out) + { out.print(getTagName() + " #"); out.print(classIndex); out.print(", name&type #"); @@ -1606,287 +1722,391 @@ abstract class MemberrefInfo extends ConstInfo { public abstract String getTagName(); } -class FieldrefInfo extends MemberrefInfo { +class FieldrefInfo extends MemberrefInfo +{ static final int tag = 9; - public FieldrefInfo(int cindex, int ntindex, int thisIndex) { + public FieldrefInfo(int cindex, int ntindex, int thisIndex) + { super(cindex, ntindex, thisIndex); } - public FieldrefInfo(DataInputStream in, int thisIndex) throws IOException { + public FieldrefInfo(DataInputStream in, int thisIndex) + throws IOException + { super(in, thisIndex); } + @Override public int getTag() { return tag; } + @Override public String getTagName() { return "Field"; } - protected int copy2(ConstPool dest, int cindex, int ntindex) { + @Override + protected int copy2(ConstPool dest, int cindex, int ntindex) + { return dest.addFieldrefInfo(cindex, ntindex); } } -class MethodrefInfo extends MemberrefInfo { +class MethodrefInfo extends MemberrefInfo +{ static final int tag = 10; - public MethodrefInfo(int cindex, int ntindex, int thisIndex) { + public MethodrefInfo(int cindex, int ntindex, int thisIndex) + { super(cindex, ntindex, thisIndex); } - public MethodrefInfo(DataInputStream in, int thisIndex) throws IOException { + public MethodrefInfo(DataInputStream in, int thisIndex) + throws IOException + { super(in, thisIndex); } + @Override public int getTag() { return tag; } + @Override public String getTagName() { return "Method"; } - protected int copy2(ConstPool dest, int cindex, int ntindex) { + @Override + protected int copy2(ConstPool dest, int cindex, int ntindex) + { return dest.addMethodrefInfo(cindex, ntindex); } } -class InterfaceMethodrefInfo extends MemberrefInfo { +class InterfaceMethodrefInfo extends MemberrefInfo +{ static final int tag = 11; - public InterfaceMethodrefInfo(int cindex, int ntindex, int thisIndex) { + public InterfaceMethodrefInfo(int cindex, int ntindex, int thisIndex) + { super(cindex, ntindex, thisIndex); } - public InterfaceMethodrefInfo(DataInputStream in, int thisIndex) throws IOException { + public InterfaceMethodrefInfo(DataInputStream in, int thisIndex) + throws IOException + { super(in, thisIndex); } + @Override public int getTag() { return tag; } + @Override public String getTagName() { return "Interface"; } - protected int copy2(ConstPool dest, int cindex, int ntindex) { + @Override + protected int copy2(ConstPool dest, int cindex, int ntindex) + { return dest.addInterfaceMethodrefInfo(cindex, ntindex); } } -class StringInfo extends ConstInfo { +class StringInfo extends ConstInfo +{ static final int tag = 8; int string; - public StringInfo(int str, int index) { + public StringInfo(int str, int index) + { super(index); string = str; } - public StringInfo(DataInputStream in, int index) throws IOException { + public StringInfo(DataInputStream in, int index) throws IOException + { super(index); string = in.readUnsignedShort(); } + @Override public int hashCode() { return string; } - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) + { return obj instanceof StringInfo && ((StringInfo)obj).string == string; } + @Override public int getTag() { return tag; } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, Map<String,String> map) + { return dest.addStringInfo(src.getUtf8Info(string)); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(tag); out.writeShort(string); } - public void print(PrintWriter out) { + @Override + public void print(PrintWriter out) + { out.print("String #"); out.println(string); } } -class IntegerInfo extends ConstInfo { +class IntegerInfo extends ConstInfo +{ static final int tag = 3; int value; - public IntegerInfo(int v, int index) { + public IntegerInfo(int v, int index) + { super(index); value = v; } - public IntegerInfo(DataInputStream in, int index) throws IOException { + public IntegerInfo(DataInputStream in, int index) throws IOException + { super(index); value = in.readInt(); } + @Override public int hashCode() { return value; } - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) + { return obj instanceof IntegerInfo && ((IntegerInfo)obj).value == value; } + @Override public int getTag() { return tag; } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, Map<String,String> map) + { return dest.addIntegerInfo(value); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(tag); out.writeInt(value); } - public void print(PrintWriter out) { + @Override + public void print(PrintWriter out) + { out.print("Integer "); out.println(value); } } -class FloatInfo extends ConstInfo { +class FloatInfo extends ConstInfo +{ static final int tag = 4; float value; - public FloatInfo(float f, int index) { + public FloatInfo(float f, int index) + { super(index); value = f; } - public FloatInfo(DataInputStream in, int index) throws IOException { + public FloatInfo(DataInputStream in, int index) throws IOException + { super(index); value = in.readFloat(); } + @Override public int hashCode() { return Float.floatToIntBits(value); } - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) + { return obj instanceof FloatInfo && ((FloatInfo)obj).value == value; } + @Override public int getTag() { return tag; } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, Map<String,String> map) + { return dest.addFloatInfo(value); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(tag); out.writeFloat(value); } - public void print(PrintWriter out) { + @Override + public void print(PrintWriter out) + { out.print("Float "); out.println(value); } } -class LongInfo extends ConstInfo { +class LongInfo extends ConstInfo +{ static final int tag = 5; long value; - public LongInfo(long l, int index) { + public LongInfo(long l, int index) + { super(index); value = l; } - public LongInfo(DataInputStream in, int index) throws IOException { + public LongInfo(DataInputStream in, int index) throws IOException + { super(index); value = in.readLong(); } + @Override public int hashCode() { return (int)(value ^ (value >>> 32)); } + @Override public boolean equals(Object obj) { return obj instanceof LongInfo && ((LongInfo)obj).value == value; } + @Override public int getTag() { return tag; } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, Map<String,String> map) + { return dest.addLongInfo(value); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(tag); out.writeLong(value); } - public void print(PrintWriter out) { + @Override + public void print(PrintWriter out) + { out.print("Long "); out.println(value); } } -class DoubleInfo extends ConstInfo { +class DoubleInfo extends ConstInfo +{ static final int tag = 6; double value; - public DoubleInfo(double d, int index) { + public DoubleInfo(double d, int index) + { super(index); value = d; } - public DoubleInfo(DataInputStream in, int index) throws IOException { + public DoubleInfo(DataInputStream in, int index) throws IOException + { super(index); value = in.readDouble(); } + @Override public int hashCode() { long v = Double.doubleToLongBits(value); return (int)(v ^ (v >>> 32)); } - public boolean equals(Object obj) { - return obj instanceof DoubleInfo && ((DoubleInfo)obj).value == value; + @Override + public boolean equals(Object obj) + { + return obj instanceof DoubleInfo + && ((DoubleInfo)obj).value == value; } + @Override public int getTag() { return tag; } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, Map<String,String> map) + { return dest.addDoubleInfo(value); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(tag); out.writeDouble(value); } - public void print(PrintWriter out) { + @Override + public void print(PrintWriter out) + { out.print("Double "); out.println(value); } } -class Utf8Info extends ConstInfo { +class Utf8Info extends ConstInfo +{ static final int tag = 1; String string; - public Utf8Info(String utf8, int index) { + public Utf8Info(String utf8, int index) + { super(index); string = utf8; } - public Utf8Info(DataInputStream in, int index) throws IOException { + public Utf8Info(DataInputStream in, int index) + throws IOException + { super(index); string = in.readUTF(); } + @Override public int hashCode() { return string.hashCode(); } + @Override public boolean equals(Object obj) { - return obj instanceof Utf8Info && ((Utf8Info)obj).string.equals(string); + return obj instanceof Utf8Info + && ((Utf8Info)obj).string.equals(string); } + @Override public int getTag() { return tag; } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, + Map<String,String> map) + { return dest.addUtf8Info(string); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) + throws IOException + { out.writeByte(tag); out.writeUTF(string); } + @Override public void print(PrintWriter out) { out.print("UTF8 \""); out.print(string); @@ -1904,36 +2124,47 @@ class MethodHandleInfo extends ConstInfo { refIndex = referenceIndex; } - public MethodHandleInfo(DataInputStream in, int index) throws IOException { + public MethodHandleInfo(DataInputStream in, int index) + throws IOException + { super(index); refKind = in.readUnsignedByte(); refIndex = in.readUnsignedShort(); } + @Override public int hashCode() { return (refKind << 16) ^ refIndex; } - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) + { if (obj instanceof MethodHandleInfo) { MethodHandleInfo mh = (MethodHandleInfo)obj; - return mh.refKind == refKind && mh.refIndex == refIndex; + return mh.refKind == refKind && mh.refIndex == refIndex; } - else - return false; + return false; } + @Override public int getTag() { return tag; } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, + Map<String,String> map) + { return dest.addMethodHandleInfo(refKind, - src.getItem(refIndex).copy(src, dest, map)); + src.getItem(refIndex).copy(src, dest, map)); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(tag); out.writeByte(refKind); out.writeShort(refIndex); } + @Override public void print(PrintWriter out) { out.print("MethodHandle #"); out.print(refKind); @@ -1942,32 +2173,42 @@ class MethodHandleInfo extends ConstInfo { } } -class MethodTypeInfo extends ConstInfo { +class MethodTypeInfo extends ConstInfo +{ static final int tag = 16; int descriptor; - public MethodTypeInfo(int desc, int index) { + public MethodTypeInfo(int desc, int index) + { super(index); descriptor = desc; } - public MethodTypeInfo(DataInputStream in, int index) throws IOException { + public MethodTypeInfo(DataInputStream in, int index) + throws IOException + { super(index); descriptor = in.readUnsignedShort(); } + @Override public int hashCode() { return descriptor; } - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) + { if (obj instanceof MethodTypeInfo) return ((MethodTypeInfo)obj).descriptor == descriptor; - else - return false; + return false; } + @Override public int getTag() { return tag; } - public void renameClass(ConstPool cp, String oldName, String newName, HashMap cache) { + @Override + public void renameClass(ConstPool cp, String oldName, String newName, + Map<ConstInfo,ConstInfo> cache) + { String desc = cp.getUtf8Info(descriptor); String desc2 = Descriptor.rename(desc, oldName, newName); if (desc != desc2) @@ -1980,7 +2221,10 @@ class MethodTypeInfo extends ConstInfo { } } - public void renameClass(ConstPool cp, Map map, HashMap cache) { + @Override + public void renameClass(ConstPool cp, Map<String,String> map, + Map<ConstInfo,ConstInfo> cache) + { String desc = cp.getUtf8Info(descriptor); String desc2 = Descriptor.rename(desc, map); if (desc != desc2) @@ -1993,63 +2237,83 @@ class MethodTypeInfo extends ConstInfo { } } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, Map<String,String> map) + { String desc = src.getUtf8Info(descriptor); desc = Descriptor.rename(desc, map); return dest.addMethodTypeInfo(dest.addUtf8Info(desc)); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(tag); out.writeShort(descriptor); } + @Override public void print(PrintWriter out) { out.print("MethodType #"); out.println(descriptor); } } -class InvokeDynamicInfo extends ConstInfo { +class InvokeDynamicInfo extends ConstInfo +{ static final int tag = 18; int bootstrap, nameAndType; - public InvokeDynamicInfo(int bootstrapMethod, int ntIndex, int index) { + public InvokeDynamicInfo(int bootstrapMethod, + int ntIndex, int index) + { super(index); bootstrap = bootstrapMethod; nameAndType = ntIndex; } - public InvokeDynamicInfo(DataInputStream in, int index) throws IOException { + public InvokeDynamicInfo(DataInputStream in, int index) + throws IOException + { super(index); bootstrap = in.readUnsignedShort(); nameAndType = in.readUnsignedShort(); } + @Override public int hashCode() { return (bootstrap << 16) ^ nameAndType; } - public boolean equals(Object obj) { + @Override + public boolean equals(Object obj) + { if (obj instanceof InvokeDynamicInfo) { InvokeDynamicInfo iv = (InvokeDynamicInfo)obj; - return iv.bootstrap == bootstrap && iv.nameAndType == nameAndType; + return iv.bootstrap == bootstrap + && iv.nameAndType == nameAndType; } - else - return false; + return false; } + @Override public int getTag() { return tag; } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, + Map<String,String> map) + { return dest.addInvokeDynamicInfo(bootstrap, - src.getItem(nameAndType).copy(src, dest, map)); + src.getItem(nameAndType).copy(src, dest, map)); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(tag); out.writeShort(bootstrap); out.writeShort(nameAndType); } + @Override public void print(PrintWriter out) { out.print("InvokeDynamic #"); out.print(bootstrap); @@ -2058,87 +2322,119 @@ class InvokeDynamicInfo extends ConstInfo { } } -class ModuleInfo extends ConstInfo { +class ModuleInfo extends ConstInfo +{ static final int tag = 19; int name; - public ModuleInfo(int moduleName, int index) { + public ModuleInfo(int moduleName, int index) + { super(index); name = moduleName; } - public ModuleInfo(DataInputStream in, int index) throws IOException { + public ModuleInfo(DataInputStream in, int index) + throws IOException + { super(index); name = in.readUnsignedShort(); } + @Override public int hashCode() { return name; } - public boolean equals(Object obj) { - return obj instanceof ModuleInfo && ((ModuleInfo)obj).name == name; + @Override + public boolean equals(Object obj) + { + return obj instanceof ModuleInfo + && ((ModuleInfo)obj).name == name; } + @Override public int getTag() { return tag; } - public String getModuleName(ConstPool cp) { + public String getModuleName(ConstPool cp) + { return cp.getUtf8Info(name); } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, + Map<String,String> map) + { String moduleName = src.getUtf8Info(name); int newName = dest.addUtf8Info(moduleName); return dest.addModuleInfo(newName); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(tag); out.writeShort(name); } + @Override public void print(PrintWriter out) { out.print("Module #"); out.println(name); } } -class PackageInfo extends ConstInfo { +class PackageInfo extends ConstInfo +{ static final int tag = 20; int name; - public PackageInfo(int moduleName, int index) { + public PackageInfo(int moduleName, int index) + { super(index); name = moduleName; } - public PackageInfo(DataInputStream in, int index) throws IOException { + public PackageInfo(DataInputStream in, int index) + throws IOException + { super(index); name = in.readUnsignedShort(); } + @Override public int hashCode() { return name; } + @Override public boolean equals(Object obj) { - return obj instanceof PackageInfo && ((PackageInfo)obj).name == name; + return obj instanceof PackageInfo + && ((PackageInfo)obj).name == name; } + @Override public int getTag() { return tag; } - public String getPackageName(ConstPool cp) { + public String getPackageName(ConstPool cp) + { return cp.getUtf8Info(name); } - public int copy(ConstPool src, ConstPool dest, Map map) { + @Override + public int copy(ConstPool src, ConstPool dest, + Map<String,String> map) + { String packageName = src.getUtf8Info(name); int newName = dest.addUtf8Info(packageName); return dest.addModuleInfo(newName); } - public void write(DataOutputStream out) throws IOException { + @Override + public void write(DataOutputStream out) throws IOException + { out.writeByte(tag); out.writeShort(name); } - public void print(PrintWriter out) { + @Override + public void print(PrintWriter out) + { out.print("Package #"); out.println(name); } diff --git a/src/main/javassist/bytecode/ConstantAttribute.java b/src/main/javassist/bytecode/ConstantAttribute.java index 0fb4cd4d..40c395c7 100644 --- a/src/main/javassist/bytecode/ConstantAttribute.java +++ b/src/main/javassist/bytecode/ConstantAttribute.java @@ -17,8 +17,8 @@ package javassist.bytecode; import java.io.DataInputStream; -import java.util.Map; import java.io.IOException; +import java.util.Map; /** * <code>ConstantValue_attribute</code>. @@ -65,7 +65,8 @@ public class ConstantAttribute extends AttributeInfo { * @param classnames pairs of replaced and substituted * class names. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { int index = getConstPool().copy(getConstantValue(), newCp, classnames); return new ConstantAttribute(newCp, index); diff --git a/src/main/javassist/bytecode/DeprecatedAttribute.java b/src/main/javassist/bytecode/DeprecatedAttribute.java index f55acebd..eaf39ef6 100644 --- a/src/main/javassist/bytecode/DeprecatedAttribute.java +++ b/src/main/javassist/bytecode/DeprecatedAttribute.java @@ -50,7 +50,8 @@ public class DeprecatedAttribute extends AttributeInfo { * @param newCp the constant pool table used by the new copy. * @param classnames should be null. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { return new DeprecatedAttribute(newCp); } } diff --git a/src/main/javassist/bytecode/Descriptor.java b/src/main/javassist/bytecode/Descriptor.java index 48cd5b8a..fc49b876 100644 --- a/src/main/javassist/bytecode/Descriptor.java +++ b/src/main/javassist/bytecode/Descriptor.java @@ -16,11 +16,12 @@ package javassist.bytecode; +import java.util.Map; + import javassist.ClassPool; import javassist.CtClass; import javassist.CtPrimitiveType; import javassist.NotFoundException; -import java.util.Map; /** * A support class for dealing with descriptors. @@ -59,8 +60,7 @@ public class Descriptor { public static String toJvmName(CtClass clazz) { if (clazz.isArray()) return of(clazz); - else - return toJvmName(clazz.getName()); + return toJvmName(clazz.getName()); } /** @@ -109,14 +109,12 @@ public class Descriptor { if (arrayDim == 0) return name; - else { - StringBuffer sbuf = new StringBuffer(name); - do { - sbuf.append("[]"); - } while (--arrayDim > 0); + StringBuffer sbuf = new StringBuffer(name); + do { + sbuf.append("[]"); + } while (--arrayDim > 0); - return sbuf.toString(); - } + return sbuf.toString(); } /** @@ -183,13 +181,11 @@ public class Descriptor { if (head == 0) return desc; - else { - int len = desc.length(); - if (head < len) - newdesc.append(desc.substring(head, len)); + int len = desc.length(); + if (head < len) + newdesc.append(desc.substring(head, len)); - return newdesc.toString(); - } + return newdesc.toString(); } /** @@ -200,7 +196,7 @@ public class Descriptor { * JVM class names. * @see Descriptor#toJvmName(String) */ - public static String rename(String desc, Map map) { + public static String rename(String desc, Map<String,String> map) { if (map == null) return desc; @@ -218,7 +214,7 @@ public class Descriptor { i = k + 1; String name = desc.substring(j + 1, k); - String name2 = (String)map.get(name); + String name2 = map.get(name); if (name2 != null) { newdesc.append(desc.substring(head, j)); newdesc.append('L'); @@ -230,13 +226,11 @@ public class Descriptor { if (head == 0) return desc; - else { - int len = desc.length(); - if (head < len) - newdesc.append(desc.substring(head, len)); + int len = desc.length(); + if (head < len) + newdesc.append(desc.substring(head, len)); - return newdesc.toString(); - } + return newdesc.toString(); } /** @@ -329,15 +323,13 @@ public class Descriptor { int i = desc.indexOf(')'); if (i < 0) return desc; - else { - StringBuffer newdesc = new StringBuffer(); - newdesc.append(desc.substring(0, i)); - newdesc.append('L'); - newdesc.append(classname.replace('.', '/')); - newdesc.append(';'); - newdesc.append(desc.substring(i)); - return newdesc.toString(); - } + StringBuffer newdesc = new StringBuffer(); + newdesc.append(desc.substring(0, i)); + newdesc.append('L'); + newdesc.append(classname.replace('.', '/')); + newdesc.append(';'); + newdesc.append(desc.substring(i)); + return newdesc.toString(); } /** @@ -353,9 +345,8 @@ public class Descriptor { public static String insertParameter(String classname, String desc) { if (desc.charAt(0) != '(') return desc; - else - return "(L" + classname.replace('.', '/') + ';' - + desc.substring(1); + return "(L" + classname.replace('.', '/') + ';' + + desc.substring(1); } /** @@ -370,13 +361,11 @@ public class Descriptor { int i = descriptor.indexOf(')'); if (i < 0) return descriptor; - else { - StringBuffer newdesc = new StringBuffer(); - newdesc.append(descriptor.substring(0, i)); - toDescriptor(newdesc, type); - newdesc.append(descriptor.substring(i)); - return newdesc.toString(); - } + StringBuffer newdesc = new StringBuffer(); + newdesc.append(descriptor.substring(0, i)); + toDescriptor(newdesc, type); + newdesc.append(descriptor.substring(i)); + return newdesc.toString(); } /** @@ -391,8 +380,7 @@ public class Descriptor { String descriptor) { if (descriptor.charAt(0) != '(') return descriptor; - else - return "(" + of(type) + descriptor.substring(1); + return "(" + of(type) + descriptor.substring(1); } /** @@ -407,14 +395,12 @@ public class Descriptor { int i = desc.indexOf(')'); if (i < 0) return desc; - else { - StringBuffer newdesc = new StringBuffer(); - newdesc.append(desc.substring(0, i + 1)); - newdesc.append('L'); - newdesc.append(classname.replace('.', '/')); - newdesc.append(';'); - return newdesc.toString(); - } + StringBuffer newdesc = new StringBuffer(); + newdesc.append(desc.substring(0, i + 1)); + newdesc.append('L'); + newdesc.append(classname.replace('.', '/')); + newdesc.append(';'); + return newdesc.toString(); } /** @@ -430,16 +416,14 @@ public class Descriptor { { if (desc.charAt(0) != '(') return null; - else { - int num = numOfParameters(desc); - CtClass[] args = new CtClass[num]; - int n = 0; - int i = 1; - do { - i = toCtClass(cp, desc, i, args, n++); - } while (i > 0); - return args; - } + int num = numOfParameters(desc); + CtClass[] args = new CtClass[num]; + int n = 0; + int i = 1; + do { + i = toCtClass(cp, desc, i, args, n++); + } while (i > 0); + return args; } /** @@ -484,11 +468,9 @@ public class Descriptor { int i = desc.indexOf(')'); if (i < 0) return null; - else { - CtClass[] type = new CtClass[1]; - toCtClass(cp, desc, i + 1, type, 0); - return type[0]; - } + CtClass[] type = new CtClass[1]; + toCtClass(cp, desc, i + 1, type, 0); + return type[0]; } /** @@ -542,11 +524,9 @@ public class Descriptor { int res = toCtClass(cp, desc, 0, clazz, 0); if (res >= 0) return clazz[0]; - else { - // maybe, you forgot to surround the class name with - // L and ;. It violates the protocol, but I'm tolerant... - return cp.get(desc.replace('/', '.')); - } + // maybe, you forgot to surround the class name with + // L and ;. It violates the protocol, but I'm tolerant... + return cp.get(desc.replace('/', '.')); } private static int toCtClass(ClassPool cp, String desc, int i, @@ -577,8 +557,7 @@ public class Descriptor { args[n] = type; return i2; // neither an array type or a class type } - else - name = type.getName(); + name = type.getName(); } if (arrayDim > 0) { diff --git a/src/main/javassist/bytecode/DuplicateMemberException.java b/src/main/javassist/bytecode/DuplicateMemberException.java index 3d763271..5a2edf57 100644 --- a/src/main/javassist/bytecode/DuplicateMemberException.java +++ b/src/main/javassist/bytecode/DuplicateMemberException.java @@ -25,6 +25,9 @@ import javassist.CannotCompileException; * @see ClassFile#addField(FieldInfo) */ public class DuplicateMemberException extends CannotCompileException { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public DuplicateMemberException(String msg) { super(msg); } diff --git a/src/main/javassist/bytecode/EnclosingMethodAttribute.java b/src/main/javassist/bytecode/EnclosingMethodAttribute.java index 4f422fd7..9eee2a0e 100644 --- a/src/main/javassist/bytecode/EnclosingMethodAttribute.java +++ b/src/main/javassist/bytecode/EnclosingMethodAttribute.java @@ -20,8 +20,6 @@ import java.io.DataInputStream; import java.io.IOException; import java.util.Map; -import javassist.CtConstructor; - /** * <code>EnclosingMethod_attribute</code>. */ @@ -108,10 +106,8 @@ public class EnclosingMethodAttribute extends AttributeInfo { int mi = methodIndex(); if (mi == 0) return MethodInfo.nameClinit; - else { - int ni = cp.getNameAndTypeName(mi); - return cp.getUtf8Info(ni); - } + int ni = cp.getNameAndTypeName(mi); + return cp.getUtf8Info(ni); } /** @@ -132,11 +128,11 @@ public class EnclosingMethodAttribute extends AttributeInfo { * @param classnames pairs of replaced and substituted * class names. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { - if (methodIndex() == 0) + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { + if (methodIndex() == 0) return new EnclosingMethodAttribute(newCp, className()); - else - return new EnclosingMethodAttribute(newCp, className(), - methodName(), methodDescriptor()); + return new EnclosingMethodAttribute(newCp, className(), + methodName(), methodDescriptor()); } } diff --git a/src/main/javassist/bytecode/ExceptionTable.java b/src/main/javassist/bytecode/ExceptionTable.java index fb6b8217..d4e5e255 100644 --- a/src/main/javassist/bytecode/ExceptionTable.java +++ b/src/main/javassist/bytecode/ExceptionTable.java @@ -20,6 +20,7 @@ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; +import java.util.List; import java.util.Map; class ExceptionTableEntry { @@ -41,7 +42,7 @@ class ExceptionTableEntry { */ public class ExceptionTable implements Cloneable { private ConstPool constPool; - private ArrayList entries; + private List<ExceptionTableEntry> entries; /** * Constructs an <code>exception_table[]</code>. @@ -50,13 +51,13 @@ public class ExceptionTable implements Cloneable { */ public ExceptionTable(ConstPool cp) { constPool = cp; - entries = new ArrayList(); + entries = new ArrayList<ExceptionTableEntry>(); } ExceptionTable(ConstPool cp, DataInputStream in) throws IOException { constPool = cp; int length = in.readUnsignedShort(); - ArrayList list = new ArrayList(length); + List<ExceptionTableEntry> list = new ArrayList<ExceptionTableEntry>(length); for (int i = 0; i < length; ++i) { int start = in.readUnsignedShort(); int end = in.readUnsignedShort(); @@ -73,9 +74,10 @@ public class ExceptionTable implements Cloneable { * The constant pool object is shared between this object * and the cloned object. */ + @Override public Object clone() throws CloneNotSupportedException { ExceptionTable r = (ExceptionTable)super.clone(); - r.entries = new ArrayList(entries); + r.entries = new ArrayList<ExceptionTableEntry>(entries); return r; } @@ -93,8 +95,7 @@ public class ExceptionTable implements Cloneable { * @param nth the <i>n</i>-th (>= 0). */ public int startPc(int nth) { - ExceptionTableEntry e = (ExceptionTableEntry)entries.get(nth); - return e.startPc; + return entries.get(nth).startPc; } /** @@ -104,8 +105,7 @@ public class ExceptionTable implements Cloneable { * @param value new value. */ public void setStartPc(int nth, int value) { - ExceptionTableEntry e = (ExceptionTableEntry)entries.get(nth); - e.startPc = value; + entries.get(nth).startPc = value; } /** @@ -114,8 +114,7 @@ public class ExceptionTable implements Cloneable { * @param nth the <i>n</i>-th (>= 0). */ public int endPc(int nth) { - ExceptionTableEntry e = (ExceptionTableEntry)entries.get(nth); - return e.endPc; + return entries.get(nth).endPc; } /** @@ -125,8 +124,7 @@ public class ExceptionTable implements Cloneable { * @param value new value. */ public void setEndPc(int nth, int value) { - ExceptionTableEntry e = (ExceptionTableEntry)entries.get(nth); - e.endPc = value; + entries.get(nth).endPc = value; } /** @@ -135,8 +133,7 @@ public class ExceptionTable implements Cloneable { * @param nth the <i>n</i>-th (>= 0). */ public int handlerPc(int nth) { - ExceptionTableEntry e = (ExceptionTableEntry)entries.get(nth); - return e.handlerPc; + return entries.get(nth).handlerPc; } /** @@ -146,8 +143,7 @@ public class ExceptionTable implements Cloneable { * @param value new value. */ public void setHandlerPc(int nth, int value) { - ExceptionTableEntry e = (ExceptionTableEntry)entries.get(nth); - e.handlerPc = value; + entries.get(nth).handlerPc = value; } /** @@ -158,8 +154,7 @@ public class ExceptionTable implements Cloneable { * or zero if this exception handler is for all exceptions. */ public int catchType(int nth) { - ExceptionTableEntry e = (ExceptionTableEntry)entries.get(nth); - return e.catchType; + return entries.get(nth).catchType; } /** @@ -169,8 +164,7 @@ public class ExceptionTable implements Cloneable { * @param value new value. */ public void setCatchType(int nth, int value) { - ExceptionTableEntry e = (ExceptionTableEntry)entries.get(nth); - e.catchType = value; + entries.get(nth).catchType = value; } /** @@ -183,8 +177,7 @@ public class ExceptionTable implements Cloneable { public void add(int index, ExceptionTable table, int offset) { int len = table.size(); while (--len >= 0) { - ExceptionTableEntry e - = (ExceptionTableEntry)table.entries.get(len); + ExceptionTableEntry e = table.entries.get(len); add(index, e.startPc + offset, e.endPc + offset, e.handlerPc + offset, e.catchType); } @@ -236,12 +229,10 @@ public class ExceptionTable implements Cloneable { * @param classnames pairs of replaced and substituted * class names. */ - public ExceptionTable copy(ConstPool newCp, Map classnames) { + public ExceptionTable copy(ConstPool newCp, Map<String,String> classnames) { ExceptionTable et = new ExceptionTable(newCp); ConstPool srcCp = constPool; - int len = size(); - for (int i = 0; i < len; ++i) { - ExceptionTableEntry e = (ExceptionTableEntry)entries.get(i); + for (ExceptionTableEntry e:entries) { int type = srcCp.copy(e.catchType, newCp, classnames); et.add(e.startPc, e.endPc, e.handlerPc, type); } @@ -250,9 +241,7 @@ public class ExceptionTable implements Cloneable { } void shiftPc(int where, int gapLength, boolean exclusive) { - int len = size(); - for (int i = 0; i < len; ++i) { - ExceptionTableEntry e = (ExceptionTableEntry)entries.get(i); + for (ExceptionTableEntry e:entries) { e.startPc = shiftPc(e.startPc, where, gapLength, exclusive); e.endPc = shiftPc(e.endPc, where, gapLength, exclusive); e.handlerPc = shiftPc(e.handlerPc, where, gapLength, exclusive); @@ -268,10 +257,8 @@ public class ExceptionTable implements Cloneable { } void write(DataOutputStream out) throws IOException { - int len = size(); - out.writeShort(len); // exception_table_length - for (int i = 0; i < len; ++i) { - ExceptionTableEntry e = (ExceptionTableEntry)entries.get(i); + out.writeShort(size()); // exception_table_length + for (ExceptionTableEntry e:entries) { out.writeShort(e.startPc); out.writeShort(e.endPc); out.writeShort(e.handlerPc); diff --git a/src/main/javassist/bytecode/ExceptionsAttribute.java b/src/main/javassist/bytecode/ExceptionsAttribute.java index 50031efd..670e51e6 100644 --- a/src/main/javassist/bytecode/ExceptionsAttribute.java +++ b/src/main/javassist/bytecode/ExceptionsAttribute.java @@ -42,7 +42,7 @@ public class ExceptionsAttribute extends AttributeInfo { * @param src source attribute. */ private ExceptionsAttribute(ConstPool cp, ExceptionsAttribute src, - Map classnames) { + Map<String,String> classnames) { super(cp, tag); copyFrom(src, classnames); } @@ -67,7 +67,8 @@ public class ExceptionsAttribute extends AttributeInfo { * @param classnames pairs of replaced and substituted * class names. It can be <code>null</code>. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { return new ExceptionsAttribute(newCp, this, classnames); } @@ -79,7 +80,7 @@ public class ExceptionsAttribute extends AttributeInfo { * @param classnames pairs of replaced and substituted * class names. */ - private void copyFrom(ExceptionsAttribute srcAttr, Map classnames) { + private void copyFrom(ExceptionsAttribute srcAttr, Map<String,String> classnames) { ConstPool srcCp = srcAttr.constPool; ConstPool destCp = this.constPool; byte[] src = srcAttr.info; diff --git a/src/main/javassist/bytecode/FieldInfo.java b/src/main/javassist/bytecode/FieldInfo.java index 926b8137..7d26327a 100644 --- a/src/main/javassist/bytecode/FieldInfo.java +++ b/src/main/javassist/bytecode/FieldInfo.java @@ -19,8 +19,8 @@ package javassist.bytecode; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; -import java.util.List; import java.util.ArrayList; +import java.util.List; /** * <code>field_info</code> structure. @@ -43,7 +43,7 @@ public final class FieldInfo { String cachedName; String cachedType; int descriptor; - ArrayList attribute; // may be null. + List<AttributeInfo> attribute; // may be null. private FieldInfo(ConstPool cp) { constPool = cp; @@ -75,6 +75,7 @@ public final class FieldInfo { /** * Returns a string representation of the object. */ + @Override public String toString() { return getName() + " " + getDescriptor(); } @@ -95,7 +96,7 @@ public final class FieldInfo { } void prune(ConstPool cp) { - ArrayList newAttributes = new ArrayList(); + List<AttributeInfo> newAttributes = new ArrayList<AttributeInfo>(); AttributeInfo invisibleAnnotations = getAttribute(AnnotationsAttribute.invisibleTag); if (invisibleAnnotations != null) { @@ -110,13 +111,13 @@ public final class FieldInfo { newAttributes.add(visibleAnnotations); } - AttributeInfo signature + AttributeInfo signature = getAttribute(SignatureAttribute.tag); if (signature != null) { signature = signature.copy(cp, null); newAttributes.add(signature); } - + int index = getConstantValue(); if (index != 0) { index = constPool.copy(index, cp, null); @@ -206,8 +207,7 @@ public final class FieldInfo { = (ConstantAttribute)getAttribute(ConstantAttribute.tag); if (attr == null) return 0; - else - return attr.getConstantValue(); + return attr.getConstantValue(); } /** @@ -220,9 +220,9 @@ public final class FieldInfo { * @return a list of <code>AttributeInfo</code> objects. * @see AttributeInfo */ - public List getAttributes() { + public List<AttributeInfo> getAttributes() { if (attribute == null) - attribute = new ArrayList(); + attribute = new ArrayList<AttributeInfo>(); return attribute; } @@ -262,7 +262,7 @@ public final class FieldInfo { */ public void addAttribute(AttributeInfo info) { if (attribute == null) - attribute = new ArrayList(); + attribute = new ArrayList<AttributeInfo>(); AttributeInfo.remove(attribute, info.getName()); attribute.add(info); @@ -273,7 +273,7 @@ public final class FieldInfo { name = in.readUnsignedShort(); descriptor = in.readUnsignedShort(); int n = in.readUnsignedShort(); - attribute = new ArrayList(); + attribute = new ArrayList<AttributeInfo>(); for (int i = 0; i < n; ++i) attribute.add(AttributeInfo.read(constPool, in)); } diff --git a/src/main/javassist/bytecode/InnerClassesAttribute.java b/src/main/javassist/bytecode/InnerClassesAttribute.java index b5b845d7..1bce893b 100644 --- a/src/main/javassist/bytecode/InnerClassesAttribute.java +++ b/src/main/javassist/bytecode/InnerClassesAttribute.java @@ -17,8 +17,8 @@ package javassist.bytecode; import java.io.DataInputStream; -import java.util.Map; import java.io.IOException; +import java.util.Map; /** * <code>InnerClasses_attribute</code>. @@ -73,8 +73,7 @@ public class InnerClassesAttribute extends AttributeInfo { int i = innerClassIndex(nth); if (i == 0) return null; - else - return constPool.getClassInfo(i); + return constPool.getClassInfo(i); } /** @@ -102,8 +101,7 @@ public class InnerClassesAttribute extends AttributeInfo { int i = outerClassIndex(nth); if (i == 0) return null; - else - return constPool.getClassInfo(i); + return constPool.getClassInfo(i); } /** @@ -131,8 +129,7 @@ public class InnerClassesAttribute extends AttributeInfo { int i = innerNameIndex(nth); if (i == 0) return null; - else - return constPool.getUtf8Info(i); + return constPool.getUtf8Info(i); } /** @@ -257,7 +254,8 @@ public class InnerClassesAttribute extends AttributeInfo { * @param classnames pairs of replaced and substituted * class names. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { byte[] src = get(); byte[] dest = new byte[src.length]; ConstPool cp = getConstPool(); diff --git a/src/main/javassist/bytecode/LineNumberAttribute.java b/src/main/javassist/bytecode/LineNumberAttribute.java index 08edb0d1..cead96e0 100644 --- a/src/main/javassist/bytecode/LineNumberAttribute.java +++ b/src/main/javassist/bytecode/LineNumberAttribute.java @@ -156,7 +156,8 @@ public class LineNumberAttribute extends AttributeInfo { * @param newCp the constant pool table used by the new copy. * @param classnames should be null. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { byte[] src = info; int num = src.length; byte[] dest = new byte[num]; diff --git a/src/main/javassist/bytecode/LocalVariableAttribute.java b/src/main/javassist/bytecode/LocalVariableAttribute.java index 6ee2791a..a0a62cc3 100644 --- a/src/main/javassist/bytecode/LocalVariableAttribute.java +++ b/src/main/javassist/bytecode/LocalVariableAttribute.java @@ -53,6 +53,7 @@ public class LocalVariableAttribute extends AttributeInfo { * @since 3.1 * @deprecated */ + @Deprecated public LocalVariableAttribute(ConstPool cp, String name) { super(cp, name, new byte[2]); ByteArray.write16bit(0, info, 0); @@ -93,6 +94,7 @@ public class LocalVariableAttribute extends AttributeInfo { info = newInfo; } + @Override void renameClass(String oldname, String newname) { ConstPool cp = getConstPool(); int n = tableLength(); @@ -111,7 +113,8 @@ public class LocalVariableAttribute extends AttributeInfo { return Descriptor.rename(desc, oldname, newname); } - void renameClass(Map classnames) { + @Override + void renameClass(Map<String,String> classnames) { ConstPool cp = getConstPool(); int n = tableLength(); for (int i = 0; i < n; ++i) { @@ -125,7 +128,7 @@ public class LocalVariableAttribute extends AttributeInfo { } } - String renameEntry(String desc, Map classnames) { + String renameEntry(String desc, Map<String,String> classnames) { return Descriptor.rename(desc, classnames); } @@ -291,7 +294,8 @@ public class LocalVariableAttribute extends AttributeInfo { * @param newCp the constant pool table used by the new copy. * @param classnames should be null. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { byte[] src = get(); byte[] dest = new byte[src.length]; ConstPool cp = getConstPool(); diff --git a/src/main/javassist/bytecode/LocalVariableTypeAttribute.java b/src/main/javassist/bytecode/LocalVariableTypeAttribute.java index 44dc8b34..12a5bf7d 100644 --- a/src/main/javassist/bytecode/LocalVariableTypeAttribute.java +++ b/src/main/javassist/bytecode/LocalVariableTypeAttribute.java @@ -49,14 +49,17 @@ public class LocalVariableTypeAttribute extends LocalVariableAttribute { super(cp, tag, dest); } + @Override String renameEntry(String desc, String oldname, String newname) { return SignatureAttribute.renameClass(desc, oldname, newname); } - String renameEntry(String desc, Map classnames) { + @Override + String renameEntry(String desc, Map<String,String> classnames) { return SignatureAttribute.renameClass(desc, classnames); } + @Override LocalVariableAttribute makeThisAttr(ConstPool cp, byte[] dest) { return new LocalVariableTypeAttribute(cp, dest); } diff --git a/src/main/javassist/bytecode/MethodInfo.java b/src/main/javassist/bytecode/MethodInfo.java index b42b7fe1..313fde99 100644 --- a/src/main/javassist/bytecode/MethodInfo.java +++ b/src/main/javassist/bytecode/MethodInfo.java @@ -59,7 +59,7 @@ public class MethodInfo { int name; String cachedName; int descriptor; - ArrayList attribute; // may be null + List<AttributeInfo> attribute; // may be null /** * If this value is true, Javassist maintains a <code>StackMap</code> attribute @@ -129,7 +129,8 @@ public class MethodInfo { * @see Descriptor */ public MethodInfo(ConstPool cp, String methodname, MethodInfo src, - Map classnameMap) throws BadBytecode { + Map<String,String> classnameMap) throws BadBytecode + { this(cp); read(src, methodname, classnameMap); } @@ -137,6 +138,7 @@ public class MethodInfo { /** * Returns a string representation of the object. */ + @Override public String toString() { return getName() + " " + getDescriptor(); } @@ -157,7 +159,7 @@ public class MethodInfo { } void prune(ConstPool cp) { - ArrayList newAttributes = new ArrayList(); + List<AttributeInfo> newAttributes = new ArrayList<AttributeInfo>(); AttributeInfo invisibleAnnotations = getAttribute(AnnotationsAttribute.invisibleTag); @@ -304,9 +306,9 @@ public class MethodInfo { * @return a list of <code>AttributeInfo</code> objects. * @see AttributeInfo */ - public List getAttributes() { + public List<AttributeInfo> getAttributes() { if (attribute == null) - attribute = new ArrayList(); + attribute = new ArrayList<AttributeInfo>(); return attribute; } @@ -347,7 +349,7 @@ public class MethodInfo { */ public void addAttribute(AttributeInfo info) { if (attribute == null) - attribute = new ArrayList(); + attribute = new ArrayList<AttributeInfo>(); AttributeInfo.remove(attribute, info.getName()); attribute.add(info); @@ -391,7 +393,7 @@ public class MethodInfo { public void setExceptionsAttribute(ExceptionsAttribute cattr) { removeExceptionsAttribute(); if (attribute == null) - attribute = new ArrayList(); + attribute = new ArrayList<AttributeInfo>(); attribute.add(cattr); } @@ -413,7 +415,7 @@ public class MethodInfo { public void setCodeAttribute(CodeAttribute cattr) { removeCodeAttribute(); if (attribute == null) - attribute = new ArrayList(); + attribute = new ArrayList<AttributeInfo>(); attribute.add(cattr); } @@ -536,8 +538,7 @@ public class MethodInfo { } } - private void read(MethodInfo src, String methodname, Map classnames) - throws BadBytecode { + private void read(MethodInfo src, String methodname, Map<String,String> classnames) { ConstPool destCp = constPool; accessFlags = src.accessFlags; name = destCp.addUtf8Info(methodname); @@ -547,7 +548,7 @@ public class MethodInfo { String desc2 = Descriptor.rename(desc, classnames); descriptor = destCp.addUtf8Info(desc2); - attribute = new ArrayList(); + attribute = new ArrayList<AttributeInfo>(); ExceptionsAttribute eattr = src.getExceptionsAttribute(); if (eattr != null) attribute.add(eattr.copy(destCp, classnames)); @@ -562,7 +563,7 @@ public class MethodInfo { name = in.readUnsignedShort(); descriptor = in.readUnsignedShort(); int n = in.readUnsignedShort(); - attribute = new ArrayList(); + attribute = new ArrayList<AttributeInfo>(); for (int i = 0; i < n; ++i) attribute.add(AttributeInfo.read(constPool, in)); } diff --git a/src/main/javassist/bytecode/MethodParametersAttribute.java b/src/main/javassist/bytecode/MethodParametersAttribute.java index b67a0f54..12521095 100644 --- a/src/main/javassist/bytecode/MethodParametersAttribute.java +++ b/src/main/javassist/bytecode/MethodParametersAttribute.java @@ -72,7 +72,8 @@ public class MethodParametersAttribute extends AttributeInfo { * @param newCp the constant pool table used by the new copy. * @param classnames ignored. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { int s = size(); ConstPool cp = getConstPool(); String[] names = new String[s]; diff --git a/src/main/javassist/bytecode/ParameterAnnotationsAttribute.java b/src/main/javassist/bytecode/ParameterAnnotationsAttribute.java index 7a69cc61..49e2646f 100644 --- a/src/main/javassist/bytecode/ParameterAnnotationsAttribute.java +++ b/src/main/javassist/bytecode/ParameterAnnotationsAttribute.java @@ -16,16 +16,17 @@ package javassist.bytecode; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.IOException; import java.util.HashMap; import java.util.Map; -import java.io.IOException; -import java.io.DataInputStream; -import java.io.ByteArrayOutputStream; import javassist.bytecode.AnnotationsAttribute.Copier; import javassist.bytecode.AnnotationsAttribute.Parser; import javassist.bytecode.AnnotationsAttribute.Renamer; -import javassist.bytecode.annotation.*; +import javassist.bytecode.annotation.Annotation; +import javassist.bytecode.annotation.AnnotationsWriter; /** * A class representing <code>RuntimeVisibleAnnotations_attribute</code> and @@ -104,7 +105,8 @@ public class ParameterAnnotationsAttribute extends AttributeInfo { /** * Copies this attribute and returns a new copy. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { Copier copier = new Copier(info, constPool, newCp, classnames); try { copier.parameters(); @@ -150,10 +152,8 @@ public class ParameterAnnotationsAttribute extends AttributeInfo { ByteArrayOutputStream output = new ByteArrayOutputStream(); AnnotationsWriter writer = new AnnotationsWriter(output, constPool); try { - int n = params.length; - writer.numParameters(n); - for (int i = 0; i < n; ++i) { - Annotation[] anno = params[i]; + writer.numParameters(params.length); + for (Annotation[] anno:params) { writer.numAnnotations(anno.length); for (int j = 0; j < anno.length; ++j) anno[j].write(writer); @@ -172,13 +172,15 @@ public class ParameterAnnotationsAttribute extends AttributeInfo { * @param oldname a JVM class name. * @param newname a JVM class name. */ + @Override void renameClass(String oldname, String newname) { - HashMap map = new HashMap(); + Map<String,String> map = new HashMap<String,String>(); map.put(oldname, newname); renameClass(map); } - void renameClass(Map classnames) { + @Override + void renameClass(Map<String,String> classnames) { Renamer renamer = new Renamer(info, getConstPool(), classnames); try { renamer.parameters(); @@ -187,29 +189,23 @@ public class ParameterAnnotationsAttribute extends AttributeInfo { } } - void getRefClasses(Map classnames) { renameClass(classnames); } + @Override + void getRefClasses(Map<String,String> classnames) { renameClass(classnames); } /** * Returns a string representation of this object. */ + @Override public String toString() { Annotation[][] aa = getAnnotations(); StringBuilder sbuf = new StringBuilder(); - int k = 0; - while (k < aa.length) { - Annotation[] a = aa[k++]; - int i = 0; - while (i < a.length) { - sbuf.append(a[i++].toString()); - if (i != a.length) - sbuf.append(" "); - } + for (Annotation[] a : aa) { + for (Annotation i : a) + sbuf.append(i.toString()).append(" "); - if (k != aa.length) - sbuf.append(", "); + sbuf.append(", "); } - return sbuf.toString(); - + return sbuf.toString().replaceAll(" (?=,)|, $",""); } } diff --git a/src/main/javassist/bytecode/SignatureAttribute.java b/src/main/javassist/bytecode/SignatureAttribute.java index 92064ee4..1a8a62dc 100644 --- a/src/main/javassist/bytecode/SignatureAttribute.java +++ b/src/main/javassist/bytecode/SignatureAttribute.java @@ -18,8 +18,11 @@ package javassist.bytecode; import java.io.DataInputStream; import java.io.IOException; -import java.util.Map; import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import javassist.CtClass; /** @@ -83,27 +86,30 @@ public class SignatureAttribute extends AttributeInfo { * @param classnames pairs of replaced and substituted * class names. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { return new SignatureAttribute(newCp, getSignature()); } + @Override void renameClass(String oldname, String newname) { String sig = renameClass(getSignature(), oldname, newname); setSignature(sig); } - void renameClass(Map classnames) { + @Override + void renameClass(Map<String,String> classnames) { String sig = renameClass(getSignature(), classnames); setSignature(sig); } static String renameClass(String desc, String oldname, String newname) { - Map map = new java.util.HashMap(); + Map<String,String> map = new HashMap<String,String>(); map.put(oldname, newname); return renameClass(desc, map); } - static String renameClass(String desc, Map map) { + static String renameClass(String desc, Map<String,String> map) { if (map == null) return desc; @@ -132,7 +138,7 @@ public class SignatureAttribute extends AttributeInfo { catch (IndexOutOfBoundsException e) { break; } i = k + 1; String name = nameBuf.toString(); - String name2 = (String)map.get(name); + String name2 = map.get(name); if (name2 != null) { newdesc.append(desc.substring(head, j)); newdesc.append('L'); @@ -144,15 +150,14 @@ public class SignatureAttribute extends AttributeInfo { if (head == 0) return desc; - else { - int len = desc.length(); - if (head < len) - newdesc.append(desc.substring(head, len)); + int len = desc.length(); + if (head < len) + newdesc.append(desc.substring(head, len)); - return newdesc.toString(); - } + return newdesc.toString(); } + @SuppressWarnings("unused") private static boolean isNamePart(int c) { return c != ';' && c != '<'; } @@ -164,10 +169,8 @@ public class SignatureAttribute extends AttributeInfo { int i = s.indexOf(ch, position); if (i < 0) throw error(s); - else { - position = i + 1; - return i; - } + position = i + 1; + return i; } } @@ -225,6 +228,7 @@ public class SignatureAttribute extends AttributeInfo { /** * Returns the string representation. */ + @Override public String toString() { StringBuffer sbuf = new StringBuffer(); @@ -314,6 +318,7 @@ public class SignatureAttribute extends AttributeInfo { /** * Returns the string representation. */ + @Override public String toString() { StringBuffer sbuf = new StringBuffer(); @@ -424,6 +429,7 @@ public class SignatureAttribute extends AttributeInfo { /** * Returns the string representation. */ + @Override public String toString() { StringBuffer sbuf = new StringBuffer(getName()); if (superClass != null) @@ -550,6 +556,7 @@ public class SignatureAttribute extends AttributeInfo { /** * Returns the string representation. */ + @Override public String toString() { if (wildcard == '*') return "?"; @@ -634,10 +641,12 @@ public class SignatureAttribute extends AttributeInfo { /** * Returns the string representation. */ + @Override public String toString() { return Descriptor.toClassName(Character.toString(descriptor)); } + @Override void encode(StringBuffer sb) { sb.append(descriptor); } @@ -669,8 +678,7 @@ public class SignatureAttribute extends AttributeInfo { TypeArgument[] targs, ClassType parent) { if (parent == null) return new ClassType(s, b, e, targs); - else - return new NestedClassType(s, b, e, targs, parent); + return new NestedClassType(s, b, e, targs, parent); } ClassType(String signature, int begin, int end, TypeArgument[] targs) { @@ -730,6 +738,7 @@ public class SignatureAttribute extends AttributeInfo { /** * Returns the string representation. */ + @Override public String toString() { StringBuffer sbuf = new StringBuffer(); ClassType parent = getDeclaringClass(); @@ -762,6 +771,7 @@ public class SignatureAttribute extends AttributeInfo { * For example, if the type is a nested class {@code foo.Bar.Baz}, * then {@code foo.Bar$Baz} is returned. */ + @Override public String jvmTypeName() { StringBuffer sbuf = new StringBuffer(); ClassType parent = getDeclaringClass(); @@ -771,6 +781,7 @@ public class SignatureAttribute extends AttributeInfo { return toString2(sbuf); } + @Override void encode(StringBuffer sb) { sb.append('L'); encode2(sb); @@ -818,6 +829,7 @@ public class SignatureAttribute extends AttributeInfo { * Returns the class that declares this nested class. * This nested class is a member of that declaring class. */ + @Override public ClassType getDeclaringClass() { return parent; } } @@ -854,6 +866,7 @@ public class SignatureAttribute extends AttributeInfo { /** * Returns the string representation. */ + @Override public String toString() { StringBuffer sbuf = new StringBuffer(componentType.toString()); for (int i = 0; i < dim; i++) @@ -862,6 +875,7 @@ public class SignatureAttribute extends AttributeInfo { return sbuf.toString(); } + @Override void encode(StringBuffer sb) { for (int i = 0; i < dim; i++) sb.append('['); @@ -899,10 +913,12 @@ public class SignatureAttribute extends AttributeInfo { /** * Returns the string representation. */ + @Override public String toString() { return name; } + @Override void encode(StringBuffer sb) { sb.append('T').append(name).append(';'); } @@ -991,12 +1007,12 @@ public class SignatureAttribute extends AttributeInfo { TypeParameter[] tp = parseTypeParams(sig, cur); ClassType superClass = parseClassType(sig, cur); int sigLen = sig.length(); - ArrayList ifArray = new ArrayList(); + List<ClassType> ifArray = new ArrayList<ClassType>(); while (cur.position < sigLen && sig.charAt(cur.position) == 'L') ifArray.add(parseClassType(sig, cur)); ClassType[] ifs - = (ClassType[])ifArray.toArray(new ClassType[ifArray.size()]); + = ifArray.toArray(new ClassType[ifArray.size()]); return new ClassSignature(tp, superClass, ifs); } @@ -1008,7 +1024,7 @@ public class SignatureAttribute extends AttributeInfo { if (sig.charAt(cur.position++) != '(') throw error(sig); - ArrayList params = new ArrayList(); + List<Type> params = new ArrayList<Type>(); while (sig.charAt(cur.position) != ')') { Type t = parseType(sig, cur); params.add(t); @@ -1017,7 +1033,7 @@ public class SignatureAttribute extends AttributeInfo { cur.position++; Type ret = parseType(sig, cur); int sigLen = sig.length(); - ArrayList exceptions = new ArrayList(); + List<ObjectType> exceptions = new ArrayList<ObjectType>(); while (cur.position < sigLen && sig.charAt(cur.position) == '^') { cur.position++; ObjectType t = parseObjectType(sig, cur, false); @@ -1027,22 +1043,22 @@ public class SignatureAttribute extends AttributeInfo { exceptions.add(t); } - Type[] p = (Type[])params.toArray(new Type[params.size()]); - ObjectType[] ex = (ObjectType[])exceptions.toArray(new ObjectType[exceptions.size()]); + Type[] p = params.toArray(new Type[params.size()]); + ObjectType[] ex = exceptions.toArray(new ObjectType[exceptions.size()]); return new MethodSignature(tp, p, ret, ex); } private static TypeParameter[] parseTypeParams(String sig, Cursor cur) throws BadBytecode { - ArrayList typeParam = new ArrayList(); + List<TypeParameter> typeParam = new ArrayList<TypeParameter>(); if (sig.charAt(cur.position) == '<') { cur.position++; while (sig.charAt(cur.position) != '>') { int nameBegin = cur.position; int nameEnd = cur.indexOf(sig, ':'); ObjectType classBound = parseObjectType(sig, cur, true); - ArrayList ifBound = new ArrayList(); + List<ObjectType> ifBound = new ArrayList<ObjectType>(); while (sig.charAt(cur.position) == ':') { cur.position++; ObjectType t = parseObjectType(sig, cur, false); @@ -1050,14 +1066,14 @@ public class SignatureAttribute extends AttributeInfo { } TypeParameter p = new TypeParameter(sig, nameBegin, nameEnd, - classBound, (ObjectType[])ifBound.toArray(new ObjectType[ifBound.size()])); + classBound, ifBound.toArray(new ObjectType[ifBound.size()])); typeParam.add(p); } cur.position++; } - return (TypeParameter[])typeParam.toArray(new TypeParameter[typeParam.size()]); + return typeParam.toArray(new TypeParameter[typeParam.size()]); } private static ObjectType parseObjectType(String sig, Cursor c, boolean dontThrow) @@ -1076,8 +1092,7 @@ public class SignatureAttribute extends AttributeInfo { default : if (dontThrow) return null; - else - throw error(sig); + throw error(sig); } } @@ -1086,8 +1101,7 @@ public class SignatureAttribute extends AttributeInfo { { if (sig.charAt(c.position) == 'L') return parseClassType2(sig, c, null); - else - throw error(sig); + throw error(sig); } private static ClassType parseClassType2(String sig, Cursor c, ClassType parent) @@ -1112,12 +1126,11 @@ public class SignatureAttribute extends AttributeInfo { c.position--; return parseClassType2(sig, c, thisClass); } - else - return thisClass; + return thisClass; } private static TypeArgument[] parseTypeArgs(String sig, Cursor c) throws BadBytecode { - ArrayList args = new ArrayList(); + List<TypeArgument> args = new ArrayList<TypeArgument>(); char t; while ((t = sig.charAt(c.position++)) != '>') { TypeArgument ta; @@ -1135,7 +1148,7 @@ public class SignatureAttribute extends AttributeInfo { args.add(ta); } - return (TypeArgument[])args.toArray(new TypeArgument[args.size()]); + return args.toArray(new TypeArgument[args.size()]); } private static ObjectType parseArray(String sig, Cursor c) throws BadBytecode { diff --git a/src/main/javassist/bytecode/SourceFileAttribute.java b/src/main/javassist/bytecode/SourceFileAttribute.java index 23ebbf3e..77d32e52 100644 --- a/src/main/javassist/bytecode/SourceFileAttribute.java +++ b/src/main/javassist/bytecode/SourceFileAttribute.java @@ -65,7 +65,8 @@ public class SourceFileAttribute extends AttributeInfo { * @param classnames pairs of replaced and substituted * class names. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { return new SourceFileAttribute(newCp, getFileName()); } } diff --git a/src/main/javassist/bytecode/StackMap.java b/src/main/javassist/bytecode/StackMap.java index 1abdc40f..96a84491 100644 --- a/src/main/javassist/bytecode/StackMap.java +++ b/src/main/javassist/bytecode/StackMap.java @@ -22,9 +22,6 @@ import java.io.IOException; import java.util.Map; import javassist.CannotCompileException; -import javassist.bytecode.StackMapTable.InsertLocal; -import javassist.bytecode.StackMapTable.NewRemover; -import javassist.bytecode.StackMapTable.Shifter; /** * Another <code>stack_map</code> attribute defined in CLDC 1.1 for J2ME. @@ -116,7 +113,8 @@ public class StackMap extends AttributeInfo { /** * Makes a copy. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { Copier copier = new Copier(this, newCp, classnames); copier.visit(); return copier.getStackMap(); @@ -224,42 +222,47 @@ public class StackMap extends AttributeInfo { static class Copier extends Walker { byte[] dest; ConstPool srcCp, destCp; - Map classnames; + Map<String,String> classnames; - Copier(StackMap map, ConstPool newCp, Map classnames) { + Copier(StackMap map, ConstPool newCp, Map<String,String> classnames) { super(map); srcCp = map.getConstPool(); dest = new byte[info.length]; destCp = newCp; this.classnames = classnames; } - + @Override public void visit() { int num = ByteArray.readU16bit(info, 0); ByteArray.write16bit(num, dest, 0); super.visit(); } + @Override public int locals(int pos, int offset, int num) { ByteArray.write16bit(offset, dest, pos - 4); return super.locals(pos, offset, num); } + @Override public int typeInfoArray(int pos, int offset, int num, boolean isLocals) { ByteArray.write16bit(num, dest, pos - 2); return super.typeInfoArray(pos, offset, num, isLocals); } + @Override public void typeInfo(int pos, byte tag) { dest[pos] = tag; } + @Override public void objectVariable(int pos, int clazz) { dest[pos] = OBJECT; int newClazz = srcCp.copy(clazz, destCp, classnames); ByteArray.write16bit(newClazz, dest, pos + 1); } + @Override public void uninitialized(int pos, int offset) { dest[pos] = UNINIT; ByteArray.write16bit(offset, dest, pos + 1); @@ -305,30 +308,36 @@ public class StackMap extends AttributeInfo { return writer.toByteArray(); } + @Override public void visit() { int num = ByteArray.readU16bit(info, 0); writer.write16bit(num); super.visit(); } + @Override public int locals(int pos, int offset, int num) { writer.write16bit(offset); return super.locals(pos, offset, num); } + @Override public int typeInfoArray(int pos, int offset, int num, boolean isLocals) { writer.write16bit(num); return super.typeInfoArray(pos, offset, num, isLocals); } + @Override public void typeInfo(int pos, byte tag) { writer.writeVerifyTypeInfo(tag, 0); } + @Override public void objectVariable(int pos, int clazz) { writer.writeVerifyTypeInfo(OBJECT, clazz); } + @Override public void uninitialized(int pos, int offset) { writer.writeVerifyTypeInfo(UNINIT, offset); } @@ -345,6 +354,7 @@ public class StackMap extends AttributeInfo { this.varData = varData; } + @Override public int typeInfoArray(int pos, int offset, int num, boolean isLocals) { if (!isLocals || num < varIndex) return super.typeInfoArray(pos, offset, num, isLocals); @@ -390,6 +400,7 @@ public class StackMap extends AttributeInfo { this.exclusive = exclusive; } + @Override public int locals(int pos, int offset, int num) { if (exclusive ? where <= offset : where < offset) ByteArray.write16bit(offset + gap, info, pos - 4); @@ -397,6 +408,7 @@ public class StackMap extends AttributeInfo { return super.locals(pos, offset, num); } + @Override public void uninitialized(int pos, int offset) { if (where <= offset) ByteArray.write16bit(offset + gap, info, pos + 1); @@ -419,6 +431,7 @@ public class StackMap extends AttributeInfo { this.gap = gap; } + @Override public int locals(int pos, int offset, int num) { if (where == pos + offset) ByteArray.write16bit(offset - gap, info, pos - 4); @@ -451,6 +464,7 @@ public class StackMap extends AttributeInfo { posOfNew = where; } + @Override public int stack(int pos, int offset, int num) { return stackTypeInfoArray(pos, offset, num); } @@ -519,6 +533,7 @@ public class StackMap extends AttributeInfo { visit(); } + @Override public int locals(int pos, int offset, int num) { writer.println(" * offset " + offset); return super.locals(pos, offset, num); diff --git a/src/main/javassist/bytecode/StackMapTable.java b/src/main/javassist/bytecode/StackMapTable.java index a02d5e72..9b8e5fae 100644 --- a/src/main/javassist/bytecode/StackMapTable.java +++ b/src/main/javassist/bytecode/StackMapTable.java @@ -16,12 +16,13 @@ package javassist.bytecode; +import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.PrintWriter; import java.io.IOException; +import java.io.PrintWriter; import java.util.Map; + import javassist.CannotCompileException; /** @@ -62,7 +63,8 @@ public class StackMapTable extends AttributeInfo { * <code>RuntimeCopyException</code>. * */ - public AttributeInfo copy(ConstPool newCp, Map classnames) + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) throws RuntimeCopyException { try { @@ -79,6 +81,9 @@ public class StackMapTable extends AttributeInfo { * in <code>StackMapTable</code>. */ public static class RuntimeCopyException extends RuntimeException { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + /** * Constructs an exception. */ @@ -87,6 +92,7 @@ public class StackMapTable extends AttributeInfo { } } + @Override void write(DataOutputStream out) throws IOException { super.write(out); } @@ -338,8 +344,8 @@ public class StackMapTable extends AttributeInfo { * @param stackData <code>stack[i].cpool_index</code> * or <code>stack[i].offset</code> */ - public void fullFrame(int pos, int offsetDelta, int[] localTags, int[] localData, - int[] stackTags, int[] stackData) + public void fullFrame(int pos, int offsetDelta, int[] localTags, + int[] localData, int[] stackTags, int[] stackData) throws BadBytecode {} private int verifyTypeInfo(int pos, int n, int[] tags, int[] data) { @@ -380,22 +386,27 @@ public class StackMapTable extends AttributeInfo { return writer.toByteArray(); } + @Override public void sameFrame(int pos, int offsetDelta) { writer.sameFrame(offsetDelta); } + @Override public void sameLocals(int pos, int offsetDelta, int stackTag, int stackData) { writer.sameLocals(offsetDelta, stackTag, copyData(stackTag, stackData)); } + @Override public void chopFrame(int pos, int offsetDelta, int k) { writer.chopFrame(offsetDelta, k); } + @Override public void appendFrame(int pos, int offsetDelta, int[] tags, int[] data) { writer.appendFrame(offsetDelta, tags, copyData(tags, data)); } + @Override public void fullFrame(int pos, int offsetDelta, int[] localTags, int[] localData, int[] stackTags, int[] stackData) { writer.fullFrame(offsetDelta, localTags, copyData(localTags, localData), @@ -413,22 +424,23 @@ public class StackMapTable extends AttributeInfo { static class Copier extends SimpleCopy { private ConstPool srcPool, destPool; - private Map classnames; + private Map<String,String> classnames; - public Copier(ConstPool src, byte[] data, ConstPool dest, Map names) { + public Copier(ConstPool src, byte[] data, ConstPool dest, Map<String,String> names) { super(data); srcPool = src; destPool = dest; classnames = names; } + @Override protected int copyData(int tag, int data) { if (tag == OBJECT) - return srcPool.copy(data, destPool, classnames); - else - return data; + return srcPool.copy(data, destPool, classnames); + return data; } + @Override protected int[] copyData(int[] tags, int[] data) { int[] newData = new int[data.length]; for (int i = 0; i < data.length; i++) @@ -504,6 +516,7 @@ public class StackMapTable extends AttributeInfo { this.varData = varData; } + @Override public void fullFrame(int pos, int offsetDelta, int[] localTags, int[] localData, int[] stackTags, int[] stackData) { int len = localTags.length; @@ -728,22 +741,26 @@ public class StackMapTable extends AttributeInfo { offset = -1; } + @Override public void sameFrame(int pos, int offsetDelta) { offset += offsetDelta + 1; writer.println(offset + " same frame: " + offsetDelta); } + @Override public void sameLocals(int pos, int offsetDelta, int stackTag, int stackData) { offset += offsetDelta + 1; writer.println(offset + " same locals: " + offsetDelta); printTypeInfo(stackTag, stackData); } + @Override public void chopFrame(int pos, int offsetDelta, int k) { offset += offsetDelta + 1; writer.println(offset + " chop frame: " + offsetDelta + ", " + k + " last locals"); } + @Override public void appendFrame(int pos, int offsetDelta, int[] tags, int[] data) { offset += offsetDelta + 1; writer.println(offset + " append frame: " + offsetDelta); @@ -751,6 +768,7 @@ public class StackMapTable extends AttributeInfo { printTypeInfo(tags[i], data[i]); } + @Override public void fullFrame(int pos, int offsetDelta, int[] localTags, int[] localData, int[] stackTags, int[] stackData) { offset += offsetDelta + 1; @@ -817,7 +835,8 @@ public class StackMapTable extends AttributeInfo { this.gap = gap; } - public void objectOrUninitialized(int tag, int data, int pos) { + @Override + public void objectOrUninitialized(int tag, int data, int pos) { if (tag == UNINIT) if (where <= data) ByteArray.write16bit(data + gap, info, pos); @@ -847,10 +866,12 @@ public class StackMapTable extends AttributeInfo { stackMap.set(updatedInfo); } + @Override public void sameFrame(int pos, int offsetDelta) { update(pos, offsetDelta, 0, 251); } + @Override public void sameLocals(int pos, int offsetDelta, int stackTag, int stackData) { update(pos, offsetDelta, 64, 247); } @@ -889,14 +910,17 @@ public class StackMapTable extends AttributeInfo { return newinfo; } + @Override public void chopFrame(int pos, int offsetDelta, int k) { update(pos, offsetDelta); } + @Override public void appendFrame(int pos, int offsetDelta, int[] tags, int[] data) { update(pos, offsetDelta); } + @Override public void fullFrame(int pos, int offsetDelta, int[] localTags, int[] localData, int[] stackTags, int[] stackData) { update(pos, offsetDelta); @@ -931,6 +955,7 @@ public class StackMapTable extends AttributeInfo { super(smt, where, gap, false); } + @Override void update(int pos, int offsetDelta, int base, int entry) { int oldPos = position; position = oldPos + offsetDelta + (oldPos == 0 ? 0 : 1); @@ -971,6 +996,7 @@ public class StackMapTable extends AttributeInfo { return newinfo; } + @Override void update(int pos, int offsetDelta) { int oldPos = position; position = oldPos + offsetDelta + (oldPos == 0 ? 0 : 1); @@ -1013,6 +1039,7 @@ public class StackMapTable extends AttributeInfo { posOfNew = pos; } + @Override public void sameLocals(int pos, int offsetDelta, int stackTag, int stackData) { if (stackTag == UNINIT && stackData == posOfNew) super.sameFrame(pos, offsetDelta); @@ -1020,6 +1047,7 @@ public class StackMapTable extends AttributeInfo { super.sameLocals(pos, offsetDelta, stackTag, stackData); } + @Override public void fullFrame(int pos, int offsetDelta, int[] localTags, int[] localData, int[] stackTags, int[] stackData) { int n = stackTags.length - 1; diff --git a/src/main/javassist/bytecode/SyntheticAttribute.java b/src/main/javassist/bytecode/SyntheticAttribute.java index a42e19b7..be6b35e1 100644 --- a/src/main/javassist/bytecode/SyntheticAttribute.java +++ b/src/main/javassist/bytecode/SyntheticAttribute.java @@ -50,7 +50,8 @@ public class SyntheticAttribute extends AttributeInfo { * @param newCp the constant pool table used by the new copy. * @param classnames should be null. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { return new SyntheticAttribute(newCp); } } diff --git a/src/main/javassist/bytecode/TypeAnnotationsAttribute.java b/src/main/javassist/bytecode/TypeAnnotationsAttribute.java index 454401a9..86fea728 100644 --- a/src/main/javassist/bytecode/TypeAnnotationsAttribute.java +++ b/src/main/javassist/bytecode/TypeAnnotationsAttribute.java @@ -4,6 +4,7 @@ import java.io.DataInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; + import javassist.bytecode.annotation.TypeAnnotationsWriter; /** @@ -57,7 +58,8 @@ public class TypeAnnotationsAttribute extends AttributeInfo { /** * Copies this attribute and returns a new copy. */ - public AttributeInfo copy(ConstPool newCp, Map classnames) { + @Override + public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { Copier copier = new Copier(info, constPool, newCp, classnames); try { copier.annotationArray(); @@ -72,13 +74,15 @@ public class TypeAnnotationsAttribute extends AttributeInfo { * @param oldname a JVM class name. * @param newname a JVM class name. */ + @Override void renameClass(String oldname, String newname) { - HashMap map = new HashMap(); + Map<String,String> map = new HashMap<String,String>(); map.put(oldname, newname); renameClass(map); } - void renameClass(Map classnames) { + @Override + void renameClass(Map<String,String> classnames) { Renamer renamer = new Renamer(info, getConstPool(), classnames); try { renamer.annotationArray(); @@ -87,7 +91,8 @@ public class TypeAnnotationsAttribute extends AttributeInfo { } } - void getRefClasses(Map classnames) { renameClass(classnames); } + @Override + void getRefClasses(Map<String,String> classnames) { renameClass(classnames); } /** * To visit each elements of the type annotation attribute, @@ -103,6 +108,7 @@ public class TypeAnnotationsAttribute extends AttributeInfo { subWalker = new SubWalker(attrInfo); } + @Override int annotationArray(int pos, int num) throws Exception { for (int i = 0; i < num; i++) { int targetType = info[pos] & 0xff; @@ -130,7 +136,7 @@ public class TypeAnnotationsAttribute extends AttributeInfo { typeParameterTarget(pos, type, index); return pos + 1; } case 0x10: { - int index = ByteArray.readU16bit(info, pos); + int index = ByteArray.readU16bit(info, pos); supertypeTarget(pos, index); return pos + 2; } case 0x11: @@ -149,22 +155,22 @@ public class TypeAnnotationsAttribute extends AttributeInfo { formalParameterTarget(pos, index); return pos + 1; } case 0x17: { - int index = ByteArray.readU16bit(info, pos); + int index = ByteArray.readU16bit(info, pos); throwsTarget(pos, index); return pos + 2; } case 0x40: case 0x41: { - int len = ByteArray.readU16bit(info, pos); + int len = ByteArray.readU16bit(info, pos); return localvarTarget(pos + 2, type, len); } case 0x42: { - int index = ByteArray.readU16bit(info, pos); + int index = ByteArray.readU16bit(info, pos); catchTarget(pos, index); return pos + 2; } case 0x43: case 0x44: case 0x45: case 0x46: { - int offset = ByteArray.readU16bit(info, pos); + int offset = ByteArray.readU16bit(info, pos); offsetTarget(pos, type, offset); return pos + 2; } case 0x47: @@ -239,11 +245,12 @@ public class TypeAnnotationsAttribute extends AttributeInfo { static class Renamer extends AnnotationsAttribute.Renamer { SubWalker sub; - Renamer(byte[] attrInfo, ConstPool cp, Map map) { + Renamer(byte[] attrInfo, ConstPool cp, Map<String,String> map) { super(attrInfo, cp, map); sub = new SubWalker(attrInfo); } + @Override int annotationArray(int pos, int num) throws Exception { for (int i = 0; i < num; i++) { int targetType = info[pos] & 0xff; @@ -259,13 +266,14 @@ public class TypeAnnotationsAttribute extends AttributeInfo { static class Copier extends AnnotationsAttribute.Copier { SubCopier sub; - Copier(byte[] attrInfo, ConstPool src, ConstPool dest, Map map) { + Copier(byte[] attrInfo, ConstPool src, ConstPool dest, Map<String,String> map) { super(attrInfo, src, dest, map, false); TypeAnnotationsWriter w = new TypeAnnotationsWriter(output, dest); writer = w; sub = new SubCopier(attrInfo, src, dest, map, w); } + @Override int annotationArray(int pos, int num) throws Exception { writer.numAnnotations(num); for (int i = 0; i < num; i++) { @@ -281,11 +289,11 @@ public class TypeAnnotationsAttribute extends AttributeInfo { static class SubCopier extends SubWalker { ConstPool srcPool, destPool; - Map classnames; + Map<String,String> classnames; TypeAnnotationsWriter writer; - SubCopier(byte[] attrInfo, ConstPool src, ConstPool dest, Map map, - TypeAnnotationsWriter w) + SubCopier(byte[] attrInfo, ConstPool src, ConstPool dest, + Map<String,String> map, TypeAnnotationsWriter w) { super(attrInfo); srcPool = src; @@ -294,16 +302,19 @@ public class TypeAnnotationsAttribute extends AttributeInfo { writer = w; } + @Override void typeParameterTarget(int pos, int targetType, int typeParameterIndex) throws Exception { - writer.typeParameterTarget(targetType, typeParameterIndex); + writer.typeParameterTarget(targetType, typeParameterIndex); } + @Override void supertypeTarget(int pos, int superTypeIndex) throws Exception { writer.supertypeTarget(superTypeIndex); } + @Override void typeParameterBoundTarget(int pos, int targetType, int typeParameterIndex, int boundIndex) throws Exception @@ -311,48 +322,58 @@ public class TypeAnnotationsAttribute extends AttributeInfo { writer.typeParameterBoundTarget(targetType, typeParameterIndex, boundIndex); } + @Override void emptyTarget(int pos, int targetType) throws Exception { writer.emptyTarget(targetType); } + @Override void formalParameterTarget(int pos, int formalParameterIndex) throws Exception { writer.formalParameterTarget(formalParameterIndex); } + @Override void throwsTarget(int pos, int throwsTypeIndex) throws Exception { writer.throwsTarget(throwsTypeIndex); } + @Override int localvarTarget(int pos, int targetType, int tableLength) throws Exception { writer.localVarTarget(targetType, tableLength); return super.localvarTarget(pos, targetType, tableLength); } + @Override void localvarTarget(int pos, int targetType, int startPc, int length, int index) throws Exception { writer.localVarTargetTable(startPc, length, index); } + @Override void catchTarget(int pos, int exceptionTableIndex) throws Exception { writer.catchTarget(exceptionTableIndex); } + @Override void offsetTarget(int pos, int targetType, int offset) throws Exception { writer.offsetTarget(targetType, offset); } + @Override void typeArgumentTarget(int pos, int targetType, int offset, int typeArgumentIndex) throws Exception { writer.typeArgumentTarget(targetType, offset, typeArgumentIndex); } + @Override int typePath(int pos, int pathLength) throws Exception { writer.typePath(pathLength); return super.typePath(pos, pathLength); } + @Override void typePath(int pos, int typePathKind, int typeArgumentIndex) throws Exception { writer.typePathPath(typePathKind, typeArgumentIndex); } diff --git a/src/main/javassist/bytecode/analysis/Analyzer.java b/src/main/javassist/bytecode/analysis/Analyzer.java index 656a1741..5d1250dd 100644 --- a/src/main/javassist/bytecode/analysis/Analyzer.java +++ b/src/main/javassist/bytecode/analysis/Analyzer.java @@ -15,8 +15,6 @@ */ package javassist.bytecode.analysis; -import java.util.Iterator; - import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; @@ -363,9 +361,7 @@ public class Analyzer implements Opcode { if (subroutine == null) throw new BadBytecode("Ret on no subroutine! [pos = " + pos + "]"); - Iterator callerIter = subroutine.callers().iterator(); - while (callerIter.hasNext()) { - int caller = ((Integer) callerIter.next()).intValue(); + for (int caller:subroutine.callers()) { int returnLoc = getNext(iter, caller, pos); boolean changed = false; @@ -377,8 +373,7 @@ public class Analyzer implements Opcode { changed = old.mergeStack(frame); } - for (Iterator i = subroutine.accessed().iterator(); i.hasNext(); ) { - int index = ((Integer)i.next()).intValue(); + for (int index:subroutine.accessed()) { Type oldType = old.getLocal(index); Type newType = frame.getLocal(index); if (oldType != newType) { diff --git a/src/main/javassist/bytecode/analysis/ControlFlow.java b/src/main/javassist/bytecode/analysis/ControlFlow.java index 0bf76a3d..e47c00d3 100644 --- a/src/main/javassist/bytecode/analysis/ControlFlow.java +++ b/src/main/javassist/bytecode/analysis/ControlFlow.java @@ -17,6 +17,8 @@ package javassist.bytecode.analysis; import java.util.ArrayList; +import java.util.List; + import javassist.CtClass; import javassist.CtMethod; import javassist.bytecode.BadBytecode; @@ -64,9 +66,11 @@ public class ControlFlow { methodInfo = minfo; frames = null; basicBlocks = (Block[])new BasicBlock.Maker() { + @Override protected BasicBlock makeBlock(int pos) { return new Block(pos, methodInfo); } + @Override protected BasicBlock[] makeArray(int size) { return new Block[size]; } @@ -156,7 +160,9 @@ public class ControlFlow { } Access access = new Access(nodes) { + @Override BasicBlock[] exits(Node n) { return n.block.getExit(); } + @Override BasicBlock[] entrances(Node n) { return n.block.entrances; } }; nodes[0].makeDepth1stTree(null, visited, 0, distance, access); @@ -202,7 +208,9 @@ public class ControlFlow { } Access access = new Access(nodes) { + @Override BasicBlock[] exits(Node n) { return n.block.entrances; } + @Override BasicBlock[] entrances(Node n) { return n.block.getExit(); } }; @@ -252,6 +260,7 @@ public class ControlFlow { method = minfo; } + @Override protected void toString2(StringBuffer sbuf) { super.toString2(sbuf); sbuf.append(", incoming{"); @@ -314,14 +323,14 @@ public class ControlFlow { * in this block. */ public Catcher[] catchers() { - ArrayList catchers = new ArrayList(); + List<Catcher> catchers = new ArrayList<Catcher>(); BasicBlock.Catch c = toCatch; while (c != null) { catchers.add(new Catcher(c)); c = c.next; } - return (Catcher[])catchers.toArray(new Catcher[catchers.size()]); + return catchers.toArray(new Catcher[catchers.size()]); } } @@ -349,6 +358,7 @@ public class ControlFlow { /** * Returns a <code>String</code> representation. */ + @Override public String toString() { StringBuffer sbuf = new StringBuffer(); sbuf.append("Node[pos=").append(block().position()); @@ -473,7 +483,7 @@ public class ControlFlow { Node n = all[i]; Node p = n.parent; if (p != null) - p.children[nchildren[p.block.index]++] = n; + p.children[nchildren[p.block.index]++] = n; } } } diff --git a/src/main/javassist/bytecode/analysis/Frame.java b/src/main/javassist/bytecode/analysis/Frame.java index 1a2b46a9..28c62e35 100644 --- a/src/main/javassist/bytecode/analysis/Frame.java +++ b/src/main/javassist/bytecode/analysis/Frame.java @@ -229,6 +229,7 @@ public class Frame { return changed; } + @Override public String toString() { StringBuffer buffer = new StringBuffer(); diff --git a/src/main/javassist/bytecode/analysis/MultiArrayType.java b/src/main/javassist/bytecode/analysis/MultiArrayType.java index 1d1b90b0..e430b850 100644 --- a/src/main/javassist/bytecode/analysis/MultiArrayType.java +++ b/src/main/javassist/bytecode/analysis/MultiArrayType.java @@ -34,6 +34,7 @@ public class MultiArrayType extends Type { this.dims = dims; } + @Override public CtClass getCtClass() { CtClass clazz = component.getCtClass(); if (clazz == null) @@ -52,30 +53,37 @@ public class MultiArrayType extends Type { } } + @Override boolean popChanged() { return component.popChanged(); } + @Override public int getDimensions() { return dims; } + @Override public Type getComponent() { return dims == 1 ? (Type)component : new MultiArrayType(component, dims - 1); } + @Override public int getSize() { return 1; } + @Override public boolean isArray() { return true; } + @Override public boolean isAssignableFrom(Type type) { throw new UnsupportedOperationException("Not implemented"); } + @Override public boolean isReference() { return true; } @@ -115,6 +123,13 @@ public class MultiArrayType extends Type { return component.isAssignableTo(typeRoot); } + + @Override + public int hashCode() { + return component.hashCode() + dims; + } + + @Override public boolean equals(Object o) { if (! (o instanceof MultiArrayType)) return false; @@ -123,6 +138,7 @@ public class MultiArrayType extends Type { return component.equals(multi.component) && dims == multi.dims; } + @Override public String toString() { // follows the same detailed formating scheme as component return arrayName(component.toString(), dims); diff --git a/src/main/javassist/bytecode/analysis/MultiType.java b/src/main/javassist/bytecode/analysis/MultiType.java index 7baa661a..a8f6fc67 100644 --- a/src/main/javassist/bytecode/analysis/MultiType.java +++ b/src/main/javassist/bytecode/analysis/MultiType.java @@ -16,7 +16,6 @@ package javassist.bytecode.analysis; import java.util.HashMap; -import java.util.Iterator; import java.util.Map; import javassist.CtClass; @@ -47,17 +46,17 @@ import javassist.CtClass; * changes, and somehow communicating assignment changes to the Analyzer */ public class MultiType extends Type { - private Map interfaces; + private Map<String,CtClass> interfaces; private Type resolved; private Type potentialClass; private MultiType mergeSource; private boolean changed = false; - public MultiType(Map interfaces) { + public MultiType(Map<String,CtClass> interfaces) { this(interfaces, null); } - public MultiType(Map interfaces, Type potentialClass) { + public MultiType(Map<String,CtClass> interfaces, Type potentialClass) { super(null); this.interfaces = interfaces; this.potentialClass = potentialClass; @@ -67,6 +66,7 @@ public class MultiType extends Type { * Gets the class that corresponds with this type. If this information * is not yet known, java.lang.Object will be returned. */ + @Override public CtClass getCtClass() { if (resolved != null) return resolved.getCtClass(); @@ -77,6 +77,7 @@ public class MultiType extends Type { /** * Always returns null since this type is never used for an array. */ + @Override public Type getComponent() { return null; } @@ -84,6 +85,7 @@ public class MultiType extends Type { /** * Always returns 1, since this type is a reference. */ + @Override public int getSize() { return 1; } @@ -91,6 +93,7 @@ public class MultiType extends Type { /** * Always reutnrs false since this type is never used for an array */ + @Override public boolean isArray() { return false; } @@ -98,12 +101,14 @@ public class MultiType extends Type { /** * Returns true if the internal state has changed. */ + @Override boolean popChanged() { boolean changed = this.changed; this.changed = false; return changed; } + @Override public boolean isAssignableFrom(Type type) { throw new UnsupportedOperationException("Not implemented"); } @@ -118,11 +123,11 @@ public class MultiType extends Type { if (potentialClass != null && !type.isAssignableFrom(potentialClass)) potentialClass = null; - Map map = mergeMultiAndSingle(this, type); + Map<String,CtClass> map = mergeMultiAndSingle(this, type); if (map.size() == 1 && potentialClass == null) { // Update previous merge paths to the same resolved type - resolved = Type.get((CtClass)map.values().iterator().next()); + resolved = Type.get(map.values().iterator().next()); propogateResolved(); return true; @@ -168,16 +173,15 @@ public class MultiType extends Type { * * @return true */ + @Override public boolean isReference() { return true; } - private Map getAllMultiInterfaces(MultiType type) { - Map map = new HashMap(); + private Map<String,CtClass> getAllMultiInterfaces(MultiType type) { + Map<String,CtClass> map = new HashMap<String,CtClass>(); - Iterator iter = type.interfaces.values().iterator(); - while (iter.hasNext()) { - CtClass intf = (CtClass)iter.next(); + for (CtClass intf:type.interfaces.values()) { map.put(intf.getName(), intf); getAllInterfaces(intf, map); } @@ -186,16 +190,16 @@ public class MultiType extends Type { } - private Map mergeMultiInterfaces(MultiType type1, MultiType type2) { - Map map1 = getAllMultiInterfaces(type1); - Map map2 = getAllMultiInterfaces(type2); + private Map<String,CtClass> mergeMultiInterfaces(MultiType type1, MultiType type2) { + Map<String,CtClass> map1 = getAllMultiInterfaces(type1); + Map<String,CtClass> map2 = getAllMultiInterfaces(type2); return findCommonInterfaces(map1, map2); } - private Map mergeMultiAndSingle(MultiType multi, Type single) { - Map map1 = getAllMultiInterfaces(multi); - Map map2 = getAllInterfaces(single.getCtClass(), null); + private Map<String,CtClass> mergeMultiAndSingle(MultiType multi, Type single) { + Map<String,CtClass> map1 = getAllMultiInterfaces(multi); + Map<String,CtClass> map2 = getAllInterfaces(single.getCtClass(), null); return findCommonInterfaces(map1, map2); } @@ -211,6 +215,7 @@ public class MultiType extends Type { return false; } + @Override public Type merge(Type type) { if (this == type) return this; @@ -235,7 +240,7 @@ public class MultiType extends Type { } } - Map merged; + Map<String,CtClass> merged; if (type instanceof MultiType) { MultiType multi = (MultiType)type; @@ -254,14 +259,13 @@ public class MultiType extends Type { // Keep all previous merge paths up to date if (merged.size() > 1 || (merged.size() == 1 && potentialClass != null)) { // Check for changes - if (merged.size() != interfaces.size()) { + if (merged.size() != interfaces.size()) changed = true; - } else if (changed == false){ - Iterator iter = merged.keySet().iterator(); - while (iter.hasNext()) - if (! interfaces.containsKey(iter.next())) + else if (changed == false) + for (String key:merged.keySet()) + if (!interfaces.containsKey(key)) changed = true; - } + interfaces = merged; propogateState(); @@ -269,19 +273,27 @@ public class MultiType extends Type { return this; } - if (merged.size() == 1) { - resolved = Type.get((CtClass) merged.values().iterator().next()); - } else if (potentialClass != null){ + if (merged.size() == 1) + resolved = Type.get(merged.values().iterator().next()); + else if (potentialClass != null) resolved = potentialClass; - } else { + else resolved = OBJECT; - } propogateResolved(); return resolved; } + @Override + public int hashCode() { + if (resolved != null) + return resolved.hashCode(); + + return interfaces.keySet().hashCode(); + } + + @Override public boolean equals(Object o) { if (! (o instanceof MultiType)) return false; @@ -295,19 +307,18 @@ public class MultiType extends Type { return interfaces.keySet().equals(multi.interfaces.keySet()); } + @Override public String toString() { if (resolved != null) return resolved.toString(); StringBuffer buffer = new StringBuffer("{"); - Iterator iter = interfaces.keySet().iterator(); - while (iter.hasNext()) { - buffer.append(iter.next()); - buffer.append(", "); - } - buffer.setLength(buffer.length() - 2); + for (String key:interfaces.keySet()) + buffer.append(key).append(", "); if (potentialClass != null) - buffer.append(", *").append(potentialClass.toString()); + buffer.append("*").append(potentialClass.toString()); + else + buffer.setLength(buffer.length() - 2); buffer.append("}"); return buffer.toString(); } diff --git a/src/main/javassist/bytecode/analysis/Subroutine.java b/src/main/javassist/bytecode/analysis/Subroutine.java index 381ed6ab..dff3084a 100644 --- a/src/main/javassist/bytecode/analysis/Subroutine.java +++ b/src/main/javassist/bytecode/analysis/Subroutine.java @@ -28,17 +28,17 @@ import java.util.Set; */ public class Subroutine { //private Set callers = new HashSet(); - private List callers = new ArrayList(); - private Set access = new HashSet(); + private List<Integer> callers = new ArrayList<Integer>(); + private Set<Integer> access = new HashSet<Integer>(); private int start; public Subroutine(int start, int caller) { this.start = start; - callers.add(Integer.valueOf(caller)); + callers.add(caller); } public void addCaller(int caller) { - callers.add(Integer.valueOf(caller)); + callers.add(caller); } public int start() { @@ -46,21 +46,22 @@ public class Subroutine { } public void access(int index) { - access.add(Integer.valueOf(index)); + access.add(index); } public boolean isAccessed(int index) { - return access.contains(Integer.valueOf(index)); + return access.contains(index); } - public Collection accessed() { + public Collection<Integer> accessed() { return access; } - public Collection callers() { + public Collection<Integer> callers() { return callers; } + @Override public String toString() { return "start = " + start + " callers = " + callers.toString(); } diff --git a/src/main/javassist/bytecode/analysis/SubroutineScanner.java b/src/main/javassist/bytecode/analysis/SubroutineScanner.java index c0af816a..f9816267 100644 --- a/src/main/javassist/bytecode/analysis/SubroutineScanner.java +++ b/src/main/javassist/bytecode/analysis/SubroutineScanner.java @@ -35,8 +35,8 @@ import javassist.bytecode.Opcode; public class SubroutineScanner implements Opcode { private Subroutine[] subroutines; - Map subTable = new HashMap(); - Set done = new HashSet(); + Map<Integer,Subroutine> subTable = new HashMap<Integer,Subroutine>(); + Set<Integer> done = new HashSet<Integer>(); public Subroutine[] scan(MethodInfo method) throws BadBytecode { @@ -62,10 +62,10 @@ public class SubroutineScanner implements Opcode { private void scan(int pos, CodeIterator iter, Subroutine sub) throws BadBytecode { // Skip already processed blocks - if (done.contains(Integer.valueOf(pos))) + if (done.contains(pos)) return; - done.add(Integer.valueOf(pos)); + done.add(pos); int old = iter.lookAhead(); iter.move(pos); @@ -103,10 +103,10 @@ public class SubroutineScanner implements Opcode { if (Util.isJumpInstruction(opcode)) { int target = Util.getJumpTarget(pos, iter); if (opcode == JSR || opcode == JSR_W) { - Subroutine s = (Subroutine) subTable.get(Integer.valueOf(target)); + Subroutine s = subTable.get(target); if (s == null) { s = new Subroutine(target, pos); - subTable.put(Integer.valueOf(target), s); + subTable.put(target, s); scan(target, iter, s); } else { s.addCaller(pos); diff --git a/src/main/javassist/bytecode/analysis/Type.java b/src/main/javassist/bytecode/analysis/Type.java index ce02c172..db02df35 100644 --- a/src/main/javassist/bytecode/analysis/Type.java +++ b/src/main/javassist/bytecode/analysis/Type.java @@ -15,10 +15,8 @@ */ package javassist.bytecode.analysis; -import java.util.ArrayList; import java.util.HashMap; import java.util.IdentityHashMap; -import java.util.Iterator; import java.util.Map; import javassist.ClassPool; @@ -44,7 +42,7 @@ public class Type { private final CtClass clazz; private final boolean special; - private static final Map prims = new IdentityHashMap(); + private static final Map<CtClass,Type> prims = new IdentityHashMap<CtClass,Type>(); /** Represents the double primitive type */ public static final Type DOUBLE = new Type(CtClass.doubleType); /** Represents the boolean primitive type */ @@ -451,7 +449,7 @@ public class Type { // If its Object, then try and find a common interface(s) if (superClass.getSuperclass() == null) { - Map interfaces = findCommonInterfaces(type); + Map<String,CtClass> interfaces = findCommonInterfaces(type); if (interfaces.size() == 1) return new Type((CtClass) interfaces.values().iterator().next()); if (interfaces.size() > 1) @@ -462,7 +460,7 @@ public class Type { } // Check for a common interface that is not on the found supertype - Map commonDeclared = findExclusiveDeclaredInterfaces(type, superClass); + Map<String,CtClass> commonDeclared = findExclusiveDeclaredInterfaces(type, superClass); if (commonDeclared.size() > 0) { return new MultiType(commonDeclared, new Type(superClass)); } @@ -470,21 +468,19 @@ public class Type { return new Type(superClass); } - private Map findCommonInterfaces(Type type) { - Map typeMap = getAllInterfaces(type.clazz, null); - Map thisMap = getAllInterfaces(this.clazz, null); + private Map<String,CtClass> findCommonInterfaces(Type type) { + Map<String,CtClass> typeMap = getAllInterfaces(type.clazz, null); + Map<String,CtClass> thisMap = getAllInterfaces(this.clazz, null); return findCommonInterfaces(typeMap, thisMap); } - private Map findExclusiveDeclaredInterfaces(Type type, CtClass exclude) { - Map typeMap = getDeclaredInterfaces(type.clazz, null); - Map thisMap = getDeclaredInterfaces(this.clazz, null); - Map excludeMap = getAllInterfaces(exclude, null); + private Map<String,CtClass> findExclusiveDeclaredInterfaces(Type type, CtClass exclude) { + Map<String,CtClass> typeMap = getDeclaredInterfaces(type.clazz, null); + Map<String,CtClass> thisMap = getDeclaredInterfaces(this.clazz, null); + Map<String,CtClass> excludeMap = getAllInterfaces(exclude, null); - Iterator i = excludeMap.keySet().iterator(); - while (i.hasNext()) { - Object intf = i.next(); + for (String intf:excludeMap.keySet()) { typeMap.remove(intf); thisMap.remove(intf); } @@ -493,19 +489,21 @@ public class Type { } - Map findCommonInterfaces(Map typeMap, Map alterMap) { - Iterator i = alterMap.keySet().iterator(); - while (i.hasNext()) { - if (! typeMap.containsKey(i.next())) - i.remove(); - } + Map<String,CtClass> findCommonInterfaces(Map<String,CtClass> typeMap, Map<String,CtClass> alterMap) { + if (alterMap == null) + alterMap = new HashMap<String,CtClass>(); + + if (typeMap == null||typeMap.isEmpty()) + alterMap.clear(); + + for (String name:alterMap.keySet()) + if (!typeMap.containsKey(name)) + alterMap.remove(name); // Reduce to subinterfaces // This does not need to be recursive since we make a copy, // and that copy contains all super types for the whole hierarchy - i = new ArrayList(alterMap.values()).iterator(); - while (i.hasNext()) { - CtClass intf = (CtClass) i.next(); + for (CtClass intf:alterMap.values()) { CtClass[] interfaces; try { interfaces = intf.getInterfaces(); @@ -513,24 +511,23 @@ public class Type { throw new RuntimeException(e); } - for (int c = 0; c < interfaces.length; c++) - alterMap.remove(interfaces[c].getName()); + for (CtClass c:interfaces) + alterMap.remove(c.getName()); } return alterMap; } - Map getAllInterfaces(CtClass clazz, Map map) { + Map<String,CtClass> getAllInterfaces(CtClass clazz, Map<String,CtClass> map) { if (map == null) - map = new HashMap(); + map = new HashMap<String,CtClass>(); if (clazz.isInterface()) map.put(clazz.getName(), clazz); do { try { CtClass[] interfaces = clazz.getInterfaces(); - for (int i = 0; i < interfaces.length; i++) { - CtClass intf = interfaces[i]; + for (CtClass intf:interfaces) { map.put(intf.getName(), intf); getAllInterfaces(intf, map); } @@ -544,9 +541,9 @@ public class Type { return map; } - Map getDeclaredInterfaces(CtClass clazz, Map map) { + Map<String,CtClass> getDeclaredInterfaces(CtClass clazz, Map<String,CtClass> map) { if (map == null) - map = new HashMap(); + map = new HashMap<String,CtClass>(); if (clazz.isInterface()) map.put(clazz.getName(), clazz); @@ -558,8 +555,7 @@ public class Type { throw new RuntimeException(e); } - for (int i = 0; i < interfaces.length; i++) { - CtClass intf = interfaces[i]; + for (CtClass intf:interfaces) { map.put(intf.getName(), intf); getDeclaredInterfaces(intf, map); } @@ -567,6 +563,12 @@ public class Type { return map; } + @Override + public int hashCode() { + return getClass().hashCode() + clazz.hashCode(); + } + + @Override public boolean equals(Object o) { if (! (o instanceof Type)) return false; @@ -578,6 +580,7 @@ public class Type { return one == two || (one != null && two != null && one.getName().equals(two.getName())); } + @Override public String toString() { if (this == BOGUS) return "BOGUS"; diff --git a/src/main/javassist/bytecode/annotation/Annotation.java b/src/main/javassist/bytecode/annotation/Annotation.java index 10ceb8ee..1cec468b 100644 --- a/src/main/javassist/bytecode/annotation/Annotation.java +++ b/src/main/javassist/bytecode/annotation/Annotation.java @@ -16,17 +16,17 @@ package javassist.bytecode.annotation; -import javassist.bytecode.ConstPool; -import javassist.bytecode.Descriptor; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; - -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Set; -import java.util.Iterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; /** * The <code>annotation</code> structure. @@ -53,7 +53,7 @@ public class Annotation { ConstPool pool; int typeIndex; - LinkedHashMap members; // this sould be LinkedHashMap + Map<String,Pair> members; // this sould be LinkedHashMap // but it is not supported by JDK 1.3. /** @@ -106,17 +106,13 @@ public class Annotation { throw new RuntimeException( "Only interfaces are allowed for Annotation creation."); - CtMethod methods[] = clazz.getDeclaredMethods(); - if (methods.length > 0) { - members = new LinkedHashMap(); - } + CtMethod[] methods = clazz.getDeclaredMethods(); + if (methods.length > 0) + members = new LinkedHashMap<String,Pair>(); - for (int i = 0; i < methods.length; i++) { - CtClass returnType = methods[i].getReturnType(); - addMemberValue(methods[i].getName(), - createMemberValue(cp, returnType)); - - } + for (CtMethod m:methods) + addMemberValue(m.getName(), + createMemberValue(cp, m.getReturnType())); } /** @@ -196,7 +192,7 @@ public class Annotation { p.name = pool.addUtf8Info(name); p.value = value; if (members == null) - members = new LinkedHashMap(); + members = new LinkedHashMap<String,Pair>(); members.put(name, p); } @@ -204,7 +200,7 @@ public class Annotation { private void addMemberValue(Pair pair) { String name = pool.getUtf8Info(pair.name); if (members == null) - members = new LinkedHashMap(); + members = new LinkedHashMap<String,Pair>(); members.put(name, pair); } @@ -212,18 +208,18 @@ public class Annotation { /** * Returns a string representation of the annotation. */ + @Override public String toString() { StringBuffer buf = new StringBuffer("@"); buf.append(getTypeName()); if (members != null) { buf.append("("); - Iterator mit = members.keySet().iterator(); - while (mit.hasNext()) { - String name = (String)mit.next(); - buf.append(name).append("=").append(getMemberValue(name)); - if (mit.hasNext()) - buf.append(", "); + for (String name:members.keySet()) { + buf.append(name).append("=") + .append(getMemberValue(name)) + .append(", "); } + buf.setLength(buf.length()-2); buf.append(")"); } @@ -244,11 +240,10 @@ public class Annotation { * * @return null if no members are defined. */ - public Set getMemberNames() { + public Set<String> getMemberNames() { if (members == null) return null; - else - return members.keySet(); + return members.keySet(); } /** @@ -267,15 +262,9 @@ public class Annotation { * @see javassist.bytecode.AnnotationDefaultAttribute */ public MemberValue getMemberValue(String name) { - if (members == null) + if (members == null||members.get(name) == null) return null; - else { - Pair p = (Pair)members.get(name); - if (p == null) - return null; - else - return p.value; - } + return members.get(name).value; } /** @@ -292,9 +281,9 @@ public class Annotation { public Object toAnnotationType(ClassLoader cl, ClassPool cp) throws ClassNotFoundException, NoSuchClassError { - Class clazz = MemberValue.loadClass(cl, getTypeName()); + Class<?> clazz = MemberValue.loadClass(cl, getTypeName()); try { - return AnnotationImpl.make(cl, clazz, cp, this); + return AnnotationImpl.make(cl, clazz, cp, this); } catch (IllegalArgumentException e) { /* AnnotationImpl.make() may throw this exception @@ -323,30 +312,35 @@ public class Annotation { } writer.annotation(typeName, members.size()); - Iterator it = members.values().iterator(); - while (it.hasNext()) { - Pair pair = (Pair)it.next(); + for (Pair pair:members.values()) { writer.memberValuePair(pair.name); pair.value.write(writer); } } + @Override + public int hashCode() { + return getTypeName().hashCode() + + (members == null ? 0 : members.hashCode()); + } + /** * Returns true if the given object represents the same annotation * as this object. The equality test checks the member values. */ + @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || obj instanceof Annotation == false) return false; - + Annotation other = (Annotation) obj; if (getTypeName().equals(other.getTypeName()) == false) return false; - LinkedHashMap otherMembers = other.members; + Map<String,Pair> otherMembers = other.members; if (members == otherMembers) return true; else if (members == null) diff --git a/src/main/javassist/bytecode/annotation/AnnotationImpl.java b/src/main/javassist/bytecode/annotation/AnnotationImpl.java index 672d2f3c..e1706098 100644 --- a/src/main/javassist/bytecode/annotation/AnnotationImpl.java +++ b/src/main/javassist/bytecode/annotation/AnnotationImpl.java @@ -38,24 +38,24 @@ import javassist.bytecode.MethodInfo; public class AnnotationImpl implements InvocationHandler { private static final String JDK_ANNOTATION_CLASS_NAME = "java.lang.annotation.Annotation"; private static Method JDK_ANNOTATION_TYPE_METHOD = null; - + private Annotation annotation; private ClassPool pool; private ClassLoader classLoader; - private transient Class annotationType; + private transient Class<?> annotationType; private transient int cachedHashCode = Integer.MIN_VALUE; static { // Try to resolve the JDK annotation type method try { - Class clazz = Class.forName(JDK_ANNOTATION_CLASS_NAME); + Class<?> clazz = Class.forName(JDK_ANNOTATION_CLASS_NAME); JDK_ANNOTATION_TYPE_METHOD = clazz.getMethod("annotationType", (Class[])null); } catch (Exception ignored) { // Probably not JDK5+ } } - + /** * Constructs an annotation object. * @@ -66,14 +66,14 @@ public class AnnotationImpl implements InvocationHandler { * @param anon the annotation. * @return the annotation */ - public static Object make(ClassLoader cl, Class clazz, ClassPool cp, + public static Object make(ClassLoader cl, Class<?> clazz, ClassPool cp, Annotation anon) throws IllegalArgumentException { AnnotationImpl handler = new AnnotationImpl(anon, cp, cl); return Proxy.newProxyInstance(cl, new Class[] { clazz }, handler); } - + private AnnotationImpl(Annotation a, ClassPool cp, ClassLoader loader) { annotation = a; pool = cp; @@ -95,7 +95,7 @@ public class AnnotationImpl implements InvocationHandler { * @return the annotation class * @throws NoClassDefFoundError when the class could not loaded */ - private Class getAnnotationType() { + private Class<?> getAnnotationType() { if (annotationType == null) { String typeName = annotation.getTypeName(); try { @@ -109,7 +109,7 @@ public class AnnotationImpl implements InvocationHandler { } return annotationType; } - + /** * Obtains the internal data structure representing the annotation. * @@ -126,6 +126,7 @@ public class AnnotationImpl implements InvocationHandler { * <code>AnnotationImpl</code>. The <code>annotationType()</code> method * is also available on the proxy instance. */ + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { @@ -147,10 +148,9 @@ public class AnnotationImpl implements InvocationHandler { MemberValue mv = annotation.getMemberValue(name); if (mv == null) return getDefault(name, method); - else - return mv.getValue(classLoader, pool, method); + return mv.getValue(classLoader, pool, method); } - + private Object getDefault(String name, Method method) throws ClassNotFoundException, RuntimeException { @@ -183,6 +183,7 @@ public class AnnotationImpl implements InvocationHandler { /** * Returns a hash code value for this object. */ + @Override public int hashCode() { if (cachedHashCode == Integer.MIN_VALUE) { int hashCode = 0; @@ -217,15 +218,15 @@ public class AnnotationImpl implements InvocationHandler { valueHashCode = arrayHashCode(value); else valueHashCode = value.hashCode(); - } + } hashCode += 127 * name.hashCode() ^ valueHashCode; } - + cachedHashCode = hashCode; } return cachedHashCode; } - + /** * Check that another annotation equals ourselves. * @@ -246,10 +247,10 @@ public class AnnotationImpl implements InvocationHandler { } } - Class otherAnnotationType = (Class) JDK_ANNOTATION_TYPE_METHOD.invoke(obj, (Object[])null); + Class<?> otherAnnotationType = (Class<?>) JDK_ANNOTATION_TYPE_METHOD.invoke(obj); if (getAnnotationType().equals(otherAnnotationType) == false) return false; - + Method[] methods = annotationType.getDeclaredMethods(); for (int i = 0; i < methods.length; ++ i) { String name = methods[i].getName(); @@ -263,7 +264,7 @@ public class AnnotationImpl implements InvocationHandler { value = mv.getValue(classLoader, pool, methods[i]); if (value == null) value = getDefault(name, methods[i]); - otherValue = methods[i].invoke(obj, (Object[])null); + otherValue = methods[i].invoke(obj); } catch (RuntimeException e) { throw e; @@ -277,7 +278,7 @@ public class AnnotationImpl implements InvocationHandler { if (value != null && value.equals(otherValue) == false) return false; } - + return true; } @@ -294,7 +295,7 @@ public class AnnotationImpl implements InvocationHandler { return 0; int result = 1; - + Object[] array = (Object[]) object; for (int i = 0; i < array.length; ++i) { int elementHashCode = 0; diff --git a/src/main/javassist/bytecode/annotation/AnnotationMemberValue.java b/src/main/javassist/bytecode/annotation/AnnotationMemberValue.java index b1237114..7691e44f 100644 --- a/src/main/javassist/bytecode/annotation/AnnotationMemberValue.java +++ b/src/main/javassist/bytecode/annotation/AnnotationMemberValue.java @@ -15,11 +15,12 @@ */ package javassist.bytecode.annotation; -import javassist.ClassPool; -import javassist.bytecode.ConstPool; import java.io.IOException; import java.lang.reflect.Method; +import javassist.ClassPool; +import javassist.bytecode.ConstPool; + /** * Nested annotation. * @@ -45,17 +46,18 @@ public class AnnotationMemberValue extends MemberValue { value = a; } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) throws ClassNotFoundException { return AnnotationImpl.make(cl, getType(cl), cp, value); } - Class getType(ClassLoader cl) throws ClassNotFoundException { + @Override + Class<?> getType(ClassLoader cl) throws ClassNotFoundException { if (value == null) throw new ClassNotFoundException("no type specified"); - else - return loadClass(cl, value.getTypeName()); + return loadClass(cl, value.getTypeName()); } /** @@ -75,6 +77,7 @@ public class AnnotationMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { return value.toString(); } @@ -82,6 +85,7 @@ public class AnnotationMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.annotationValue(); value.write(writer); @@ -90,6 +94,7 @@ public class AnnotationMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitAnnotationMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/AnnotationsWriter.java b/src/main/javassist/bytecode/annotation/AnnotationsWriter.java index e2203d4e..8095fbe1 100644 --- a/src/main/javassist/bytecode/annotation/AnnotationsWriter.java +++ b/src/main/javassist/bytecode/annotation/AnnotationsWriter.java @@ -16,7 +16,8 @@ package javassist.bytecode.annotation; -import java.io.*; +import java.io.IOException; +import java.io.OutputStream; import javassist.bytecode.ByteArray; import javassist.bytecode.ConstPool; diff --git a/src/main/javassist/bytecode/annotation/ArrayMemberValue.java b/src/main/javassist/bytecode/annotation/ArrayMemberValue.java index 389bdf90..d1eeb271 100644 --- a/src/main/javassist/bytecode/annotation/ArrayMemberValue.java +++ b/src/main/javassist/bytecode/annotation/ArrayMemberValue.java @@ -15,12 +15,13 @@ */ package javassist.bytecode.annotation; -import javassist.ClassPool; -import javassist.bytecode.ConstPool; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Method; +import javassist.ClassPool; +import javassist.bytecode.ConstPool; + /** * Array member. * @@ -51,6 +52,7 @@ public class ArrayMemberValue extends MemberValue { values = null; } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method method) throws ClassNotFoundException { @@ -59,7 +61,7 @@ public class ArrayMemberValue extends MemberValue { "no array elements found: " + method.getName()); int size = values.length; - Class clazz; + Class<?> clazz; if (type == null) { clazz = method.getReturnType().getComponentType(); if (clazz == null || size > 0) @@ -76,7 +78,8 @@ public class ArrayMemberValue extends MemberValue { return a; } - Class getType(ClassLoader cl) throws ClassNotFoundException { + @Override + Class<?> getType(ClassLoader cl) throws ClassNotFoundException { if (type == null) throw new ClassNotFoundException("no array type specified"); @@ -112,6 +115,7 @@ public class ArrayMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { StringBuffer buf = new StringBuffer("{"); if (values != null) { @@ -129,6 +133,7 @@ public class ArrayMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { int num = values == null ? 0 : values.length; writer.arrayValue(num); @@ -139,6 +144,7 @@ public class ArrayMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitArrayMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/BooleanMemberValue.java b/src/main/javassist/bytecode/annotation/BooleanMemberValue.java index b005ad5a..c9ec3c32 100644 --- a/src/main/javassist/bytecode/annotation/BooleanMemberValue.java +++ b/src/main/javassist/bytecode/annotation/BooleanMemberValue.java @@ -15,11 +15,12 @@ */ package javassist.bytecode.annotation; -import javassist.ClassPool; -import javassist.bytecode.ConstPool; import java.io.IOException; import java.lang.reflect.Method; +import javassist.ClassPool; +import javassist.bytecode.ConstPool; + /** * Boolean constant value. * @@ -58,11 +59,13 @@ public class BooleanMemberValue extends MemberValue { setValue(false); } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) { return Boolean.valueOf(getValue()); } - Class getType(ClassLoader cl) { + @Override + Class<?> getType(ClassLoader cl) { return boolean.class; } @@ -83,6 +86,7 @@ public class BooleanMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { return getValue() ? "true" : "false"; } @@ -90,6 +94,7 @@ public class BooleanMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.constValueIndex(getValue()); } @@ -97,6 +102,7 @@ public class BooleanMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitBooleanMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/ByteMemberValue.java b/src/main/javassist/bytecode/annotation/ByteMemberValue.java index d0fb5c61..be3f6e2e 100644 --- a/src/main/javassist/bytecode/annotation/ByteMemberValue.java +++ b/src/main/javassist/bytecode/annotation/ByteMemberValue.java @@ -15,11 +15,12 @@ */ package javassist.bytecode.annotation; -import javassist.ClassPool; -import javassist.bytecode.ConstPool; import java.io.IOException; import java.lang.reflect.Method; +import javassist.ClassPool; +import javassist.bytecode.ConstPool; + /** * Byte constant value. * @@ -58,11 +59,13 @@ public class ByteMemberValue extends MemberValue { setValue((byte)0); } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) { return Byte.valueOf(getValue()); } - Class getType(ClassLoader cl) { + @Override + Class<?> getType(ClassLoader cl) { return byte.class; } @@ -83,6 +86,7 @@ public class ByteMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { return Byte.toString(getValue()); } @@ -90,6 +94,7 @@ public class ByteMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.constValueIndex(getValue()); } @@ -97,6 +102,7 @@ public class ByteMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitByteMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/CharMemberValue.java b/src/main/javassist/bytecode/annotation/CharMemberValue.java index ce5d4199..bf8d7b44 100644 --- a/src/main/javassist/bytecode/annotation/CharMemberValue.java +++ b/src/main/javassist/bytecode/annotation/CharMemberValue.java @@ -16,11 +16,12 @@ package javassist.bytecode.annotation; -import javassist.ClassPool; -import javassist.bytecode.ConstPool; import java.io.IOException; import java.lang.reflect.Method; +import javassist.ClassPool; +import javassist.bytecode.ConstPool; + /** * Char constant value. * @@ -59,11 +60,13 @@ public class CharMemberValue extends MemberValue { setValue('\0'); } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) { return Character.valueOf(getValue()); } - Class getType(ClassLoader cl) { + @Override + Class<?> getType(ClassLoader cl) { return char.class; } @@ -84,6 +87,7 @@ public class CharMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { return Character.toString(getValue()); } @@ -91,6 +95,7 @@ public class CharMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.constValueIndex(getValue()); } @@ -98,6 +103,7 @@ public class CharMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitCharMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/ClassMemberValue.java b/src/main/javassist/bytecode/annotation/ClassMemberValue.java index 7169d723..e9fd7ec4 100644 --- a/src/main/javassist/bytecode/annotation/ClassMemberValue.java +++ b/src/main/javassist/bytecode/annotation/ClassMemberValue.java @@ -16,15 +16,15 @@ package javassist.bytecode.annotation; +import java.io.IOException; +import java.lang.reflect.Method; + import javassist.ClassPool; import javassist.bytecode.BadBytecode; import javassist.bytecode.ConstPool; import javassist.bytecode.Descriptor; import javassist.bytecode.SignatureAttribute; -import java.io.IOException; -import java.lang.reflect.Method; - /** * Class value. * @@ -64,6 +64,7 @@ public class ClassMemberValue extends MemberValue { setValue("java.lang.Class"); } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) throws ClassNotFoundException { final String classname = getValue(); @@ -89,7 +90,8 @@ public class ClassMemberValue extends MemberValue { return loadClass(cl, classname); } - Class getType(ClassLoader cl) throws ClassNotFoundException { + @Override + Class<?> getType(ClassLoader cl) throws ClassNotFoundException { return loadClass(cl, "java.lang.Class"); } @@ -120,6 +122,7 @@ public class ClassMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { return getValue().replace('$', '.') + ".class"; } @@ -127,6 +130,7 @@ public class ClassMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.classInfoIndex(cp.getUtf8Info(valueIndex)); } @@ -134,6 +138,7 @@ public class ClassMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitClassMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/DoubleMemberValue.java b/src/main/javassist/bytecode/annotation/DoubleMemberValue.java index 0f18a72d..3d9fdb28 100644 --- a/src/main/javassist/bytecode/annotation/DoubleMemberValue.java +++ b/src/main/javassist/bytecode/annotation/DoubleMemberValue.java @@ -16,11 +16,12 @@ package javassist.bytecode.annotation; -import javassist.ClassPool; -import javassist.bytecode.ConstPool; import java.io.IOException; import java.lang.reflect.Method; +import javassist.ClassPool; +import javassist.bytecode.ConstPool; + /** * Double floating-point number constant value. * @@ -60,11 +61,13 @@ public class DoubleMemberValue extends MemberValue { setValue(0.0); } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) { return Double.valueOf(getValue()); } - Class getType(ClassLoader cl) { + @Override + Class<?> getType(ClassLoader cl) { return double.class; } @@ -85,6 +88,7 @@ public class DoubleMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { return Double.toString(getValue()); } @@ -92,6 +96,7 @@ public class DoubleMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.constValueIndex(getValue()); } @@ -99,6 +104,7 @@ public class DoubleMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitDoubleMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/EnumMemberValue.java b/src/main/javassist/bytecode/annotation/EnumMemberValue.java index a051b3a4..a0a4e036 100644 --- a/src/main/javassist/bytecode/annotation/EnumMemberValue.java +++ b/src/main/javassist/bytecode/annotation/EnumMemberValue.java @@ -56,6 +56,7 @@ public class EnumMemberValue extends MemberValue { typeIndex = valueIndex = 0; } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) throws ClassNotFoundException { @@ -70,7 +71,8 @@ public class EnumMemberValue extends MemberValue { } } - Class getType(ClassLoader cl) throws ClassNotFoundException { + @Override + Class<?> getType(ClassLoader cl) throws ClassNotFoundException { return loadClass(cl, getType()); } @@ -86,7 +88,7 @@ public class EnumMemberValue extends MemberValue { /** * Changes the enum type name. * - * @param typename a fully-qualified type name. + * @param typename a fully-qualified type name. */ public void setType(String typename) { typeIndex = cp.addUtf8Info(Descriptor.of(typename)); @@ -106,6 +108,7 @@ public class EnumMemberValue extends MemberValue { valueIndex = cp.addUtf8Info(name); } + @Override public String toString() { return getType() + "." + getValue(); } @@ -113,6 +116,7 @@ public class EnumMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.enumConstValue(cp.getUtf8Info(typeIndex), getValue()); } @@ -120,6 +124,7 @@ public class EnumMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitEnumMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/FloatMemberValue.java b/src/main/javassist/bytecode/annotation/FloatMemberValue.java index 3bf07ef0..ef993792 100644 --- a/src/main/javassist/bytecode/annotation/FloatMemberValue.java +++ b/src/main/javassist/bytecode/annotation/FloatMemberValue.java @@ -16,11 +16,12 @@ package javassist.bytecode.annotation; -import javassist.ClassPool; -import javassist.bytecode.ConstPool; import java.io.IOException; import java.lang.reflect.Method; +import javassist.ClassPool; +import javassist.bytecode.ConstPool; + /** * Floating-point number constant value. * @@ -60,11 +61,13 @@ public class FloatMemberValue extends MemberValue { setValue(0.0F); } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) { return Float.valueOf(getValue()); } - Class getType(ClassLoader cl) { + @Override + Class<?> getType(ClassLoader cl) { return float.class; } @@ -85,6 +88,7 @@ public class FloatMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { return Float.toString(getValue()); } @@ -92,6 +96,7 @@ public class FloatMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.constValueIndex(getValue()); } @@ -99,6 +104,7 @@ public class FloatMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitFloatMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/IntegerMemberValue.java b/src/main/javassist/bytecode/annotation/IntegerMemberValue.java index 83e4e70f..538b620c 100644 --- a/src/main/javassist/bytecode/annotation/IntegerMemberValue.java +++ b/src/main/javassist/bytecode/annotation/IntegerMemberValue.java @@ -16,11 +16,12 @@ package javassist.bytecode.annotation; -import javassist.ClassPool; -import javassist.bytecode.ConstPool; import java.io.IOException; import java.lang.reflect.Method; +import javassist.ClassPool; +import javassist.bytecode.ConstPool; + /** * Integer constant value. * @@ -65,11 +66,13 @@ public class IntegerMemberValue extends MemberValue { setValue(0); } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) { return Integer.valueOf(getValue()); } - Class getType(ClassLoader cl) { + @Override + Class<?> getType(ClassLoader cl) { return int.class; } @@ -90,6 +93,7 @@ public class IntegerMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { return Integer.toString(getValue()); } @@ -97,6 +101,7 @@ public class IntegerMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.constValueIndex(getValue()); } @@ -104,6 +109,7 @@ public class IntegerMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitIntegerMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/LongMemberValue.java b/src/main/javassist/bytecode/annotation/LongMemberValue.java index 7f0c6fec..3dd29a37 100644 --- a/src/main/javassist/bytecode/annotation/LongMemberValue.java +++ b/src/main/javassist/bytecode/annotation/LongMemberValue.java @@ -16,11 +16,12 @@ package javassist.bytecode.annotation; -import javassist.ClassPool; -import javassist.bytecode.ConstPool; import java.io.IOException; import java.lang.reflect.Method; +import javassist.ClassPool; +import javassist.bytecode.ConstPool; + /** * Long integer constant value. * @@ -59,11 +60,13 @@ public class LongMemberValue extends MemberValue { setValue(0L); } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) { return Long.valueOf(getValue()); } - Class getType(ClassLoader cl) { + @Override + Class<?> getType(ClassLoader cl) { return long.class; } @@ -84,6 +87,7 @@ public class LongMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { return Long.toString(getValue()); } @@ -91,6 +95,7 @@ public class LongMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.constValueIndex(getValue()); } @@ -98,6 +103,7 @@ public class LongMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitLongMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/MemberValue.java b/src/main/javassist/bytecode/annotation/MemberValue.java index ab60c959..da99885c 100644 --- a/src/main/javassist/bytecode/annotation/MemberValue.java +++ b/src/main/javassist/bytecode/annotation/MemberValue.java @@ -16,14 +16,13 @@ package javassist.bytecode.annotation; +import java.io.IOException; +import java.lang.reflect.Method; + import javassist.ClassPool; import javassist.bytecode.ConstPool; import javassist.bytecode.Descriptor; -import java.io.IOException; -import java.lang.reflect.Array; -import java.lang.reflect.Method; - /** * The value of a member declared in an annotation. * @@ -47,9 +46,9 @@ public abstract class MemberValue { abstract Object getValue(ClassLoader cl, ClassPool cp, Method m) throws ClassNotFoundException; - abstract Class getType(ClassLoader cl) throws ClassNotFoundException; + abstract Class<?> getType(ClassLoader cl) throws ClassNotFoundException; - static Class loadClass(ClassLoader cl, String classname) + static Class<?> loadClass(ClassLoader cl, String classname) throws ClassNotFoundException, NoSuchClassError { try { @@ -59,10 +58,10 @@ public abstract class MemberValue { throw new NoSuchClassError(classname, e); } } - + private static String convertFromArray(String classname) { - int index = classname.indexOf("[]"); + int index = classname.indexOf("[]"); if (index != -1) { String rawType = classname.substring(0, index); StringBuffer sb = new StringBuffer(Descriptor.of(rawType)); diff --git a/src/main/javassist/bytecode/annotation/NoSuchClassError.java b/src/main/javassist/bytecode/annotation/NoSuchClassError.java index 64187f8c..a2b23b34 100644 --- a/src/main/javassist/bytecode/annotation/NoSuchClassError.java +++ b/src/main/javassist/bytecode/annotation/NoSuchClassError.java @@ -21,6 +21,8 @@ package javassist.bytecode.annotation; * It keeps the name of the class that caused this error. */ public class NoSuchClassError extends Error { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private String className; /** diff --git a/src/main/javassist/bytecode/annotation/ShortMemberValue.java b/src/main/javassist/bytecode/annotation/ShortMemberValue.java index 82a6f59e..277c2820 100644 --- a/src/main/javassist/bytecode/annotation/ShortMemberValue.java +++ b/src/main/javassist/bytecode/annotation/ShortMemberValue.java @@ -16,11 +16,12 @@ package javassist.bytecode.annotation; -import javassist.ClassPool; -import javassist.bytecode.ConstPool; import java.io.IOException; import java.lang.reflect.Method; +import javassist.ClassPool; +import javassist.bytecode.ConstPool; + /** * Short integer constant value. * @@ -59,11 +60,13 @@ public class ShortMemberValue extends MemberValue { setValue((short)0); } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) { return Short.valueOf(getValue()); } - Class getType(ClassLoader cl) { + @Override + Class<?> getType(ClassLoader cl) { return short.class; } @@ -84,6 +87,7 @@ public class ShortMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { return Short.toString(getValue()); } @@ -91,6 +95,7 @@ public class ShortMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.constValueIndex(getValue()); } @@ -98,6 +103,7 @@ public class ShortMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitShortMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/StringMemberValue.java b/src/main/javassist/bytecode/annotation/StringMemberValue.java index 7e83f923..48fe1f6e 100644 --- a/src/main/javassist/bytecode/annotation/StringMemberValue.java +++ b/src/main/javassist/bytecode/annotation/StringMemberValue.java @@ -16,11 +16,12 @@ package javassist.bytecode.annotation; -import javassist.ClassPool; -import javassist.bytecode.ConstPool; import java.io.IOException; import java.lang.reflect.Method; +import javassist.ClassPool; +import javassist.bytecode.ConstPool; + /** * String constant value. * @@ -59,11 +60,13 @@ public class StringMemberValue extends MemberValue { setValue(""); } + @Override Object getValue(ClassLoader cl, ClassPool cp, Method m) { return getValue(); } - Class getType(ClassLoader cl) { + @Override + Class<?> getType(ClassLoader cl) { return String.class; } @@ -84,6 +87,7 @@ public class StringMemberValue extends MemberValue { /** * Obtains the string representation of this object. */ + @Override public String toString() { return "\"" + getValue() + "\""; } @@ -91,6 +95,7 @@ public class StringMemberValue extends MemberValue { /** * Writes the value. */ + @Override public void write(AnnotationsWriter writer) throws IOException { writer.constValueIndex(getValue()); } @@ -98,6 +103,7 @@ public class StringMemberValue extends MemberValue { /** * Accepts a visitor. */ + @Override public void accept(MemberValueVisitor visitor) { visitor.visitStringMemberValue(this); } diff --git a/src/main/javassist/bytecode/annotation/TypeAnnotationsWriter.java b/src/main/javassist/bytecode/annotation/TypeAnnotationsWriter.java index d9a61692..6f765b41 100644 --- a/src/main/javassist/bytecode/annotation/TypeAnnotationsWriter.java +++ b/src/main/javassist/bytecode/annotation/TypeAnnotationsWriter.java @@ -28,6 +28,7 @@ public class TypeAnnotationsWriter extends AnnotationsWriter { * {@code Runtime(In)VisibleTypeAnnotations_attribute}. * It must be followed by {@code num} instances of {@code type_annotation}. */ + @Override public void numAnnotations(int num) throws IOException { super.numAnnotations(num); } diff --git a/src/main/javassist/bytecode/stackmap/BasicBlock.java b/src/main/javassist/bytecode/stackmap/BasicBlock.java index 7a643609..231ffc3a 100644 --- a/src/main/javassist/bytecode/stackmap/BasicBlock.java +++ b/src/main/javassist/bytecode/stackmap/BasicBlock.java @@ -16,9 +16,18 @@ package javassist.bytecode.stackmap; -import javassist.bytecode.*; -import java.util.HashMap; import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javassist.bytecode.BadBytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ExceptionTable; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; /** * A basic block is a sequence of bytecode that does not contain jump/branch @@ -28,6 +37,9 @@ import java.util.ArrayList; */ public class BasicBlock { static class JsrBytecode extends BadBytecode { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + JsrBytecode() { super("JSR"); } } @@ -46,11 +58,9 @@ public class BasicBlock { public static BasicBlock find(BasicBlock[] blocks, int pos) throws BadBytecode { - for (int i = 0; i < blocks.length; i++) { - int iPos = blocks[i].position; - if (iPos <= pos && pos < iPos + blocks[i].length) - return blocks[i]; - } + for (BasicBlock b:blocks) + if (b.position <= pos && pos < b.position + b.length) + return b; throw new BadBytecode("no basic block at " + pos); } @@ -66,6 +76,7 @@ public class BasicBlock { } } + @Override public String toString() { StringBuffer sbuf = new StringBuffer(); String cname = this.getClass().getName(); @@ -81,10 +92,9 @@ public class BasicBlock { sbuf.append("pos=").append(position).append(", len=") .append(length).append(", in=").append(incoming) .append(", exit{"); - if (exit != null) { - for (int i = 0; i < exit.length; i++) - sbuf.append(exit[i].position).append(","); - } + if (exit != null) + for (BasicBlock b:exit) + sbuf.append(b.position).append(","); sbuf.append("}, {"); Catch th = toCatch; @@ -101,7 +111,7 @@ public class BasicBlock { * A Mark indicates the position of a branch instruction * or a branch target. */ - static class Mark implements Comparable { + static class Mark implements Comparable<Mark> { int position; BasicBlock block; BasicBlock[] jump; @@ -118,13 +128,11 @@ public class BasicBlock { catcher = null; } - public int compareTo(Object obj) { - if (obj instanceof Mark) { - int pos = ((Mark)obj).position; - return position - pos; - } - - return -1; + @Override + public int compareTo(Mark obj) { + if (null == obj) + return -1; + return position - obj.position; } void setJump(BasicBlock[] bb, int s, boolean always) { @@ -172,7 +180,7 @@ public class BasicBlock { ExceptionTable et) throws BadBytecode { - HashMap marks = makeMarks(ci, begin, end, et); + Map<Integer,Mark> marks = makeMarks(ci, begin, end, et); BasicBlock[] bb = makeBlocks(marks); addCatchers(bb, et); return bb; @@ -180,24 +188,24 @@ public class BasicBlock { /* Branch target */ - private Mark makeMark(HashMap table, int pos) { + private Mark makeMark(Map<Integer,Mark> table, int pos) { return makeMark0(table, pos, true, true); } /* Branch instruction. * size > 0 */ - private Mark makeMark(HashMap table, int pos, BasicBlock[] jump, + private Mark makeMark(Map<Integer,Mark> table, int pos, BasicBlock[] jump, int size, boolean always) { Mark m = makeMark0(table, pos, false, false); m.setJump(jump, size, always); return m; } - private Mark makeMark0(HashMap table, int pos, + private Mark makeMark0(Map<Integer,Mark> table, int pos, boolean isBlockBegin, boolean isTarget) { - Integer p = Integer.valueOf(pos); - Mark m = (Mark)table.get(p); + Integer p = pos; + Mark m = table.get(p); if (m == null) { m = new Mark(pos); table.put(p, m); @@ -214,13 +222,13 @@ public class BasicBlock { return m; } - private HashMap makeMarks(CodeIterator ci, int begin, int end, + private Map<Integer,Mark> makeMarks(CodeIterator ci, int begin, int end, ExceptionTable et) throws BadBytecode { ci.begin(); ci.move(begin); - HashMap marks = new HashMap(); + Map<Integer,Mark> marks = new HashMap<Integer,Mark>(); while (ci.hasNext()) { int index = ci.next(); if (index >= end) @@ -296,7 +304,7 @@ public class BasicBlock { return marks; } - private void makeGoto(HashMap marks, int pos, int target, int size) { + private void makeGoto(Map<Integer,Mark> marks, int pos, int target, int size) { Mark to = makeMark(marks, target); BasicBlock[] jumps = makeArray(to.block); makeMark(marks, pos, jumps, size, true); @@ -306,7 +314,7 @@ public class BasicBlock { * We could ignore JSR since Java 7 or later does not allow it. * See The JVM Spec. Sec. 4.10.2.5. */ - protected void makeJsr(HashMap marks, int pos, int target, int size) throws BadBytecode { + protected void makeJsr(Map<Integer,Mark> marks, int pos, int target, int size) throws BadBytecode { /* Mark to = makeMark(marks, target); Mark next = makeMark(marks, pos + size); @@ -316,11 +324,10 @@ public class BasicBlock { throw new JsrBytecode(); } - private BasicBlock[] makeBlocks(HashMap markTable) { - Mark[] marks = (Mark[])markTable.values() - .toArray(new Mark[markTable.size()]); - java.util.Arrays.sort(marks); - ArrayList blocks = new ArrayList(); + private BasicBlock[] makeBlocks(Map<Integer,Mark> markTable) { + Mark[] marks = markTable.values().toArray(new Mark[markTable.size()]); + Arrays.sort(marks); + List<BasicBlock> blocks = new ArrayList<BasicBlock>(); int i = 0; BasicBlock prev; if (marks.length > 0 && marks[0].position == 0 && marks[0].block != null) @@ -370,7 +377,7 @@ public class BasicBlock { } } - return (BasicBlock[])blocks.toArray(makeArray(blocks.size())); + return blocks.toArray(makeArray(blocks.size())); } private static BasicBlock getBBlock(Mark m) { diff --git a/src/main/javassist/bytecode/stackmap/MapMaker.java b/src/main/javassist/bytecode/stackmap/MapMaker.java index 5c4d7a53..538fba67 100644 --- a/src/main/javassist/bytecode/stackmap/MapMaker.java +++ b/src/main/javassist/bytecode/stackmap/MapMaker.java @@ -17,10 +17,18 @@ package javassist.bytecode.stackmap; import java.util.ArrayList; +import java.util.List; + import javassist.ClassPool; -import javassist.CtClass; import javassist.NotFoundException; -import javassist.bytecode.*; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.ByteArray; +import javassist.bytecode.Bytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.ConstPool; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.StackMap; +import javassist.bytecode.StackMapTable; /** * Stack map maker. @@ -379,7 +387,7 @@ public class MapMaker extends Tracer { * their types are also fixed when they are found. */ private void fixTypes(byte[] code, TypedBlock[] blocks) throws NotFoundException, BadBytecode { - ArrayList preOrder = new ArrayList(); + List<TypeData> preOrder = new ArrayList<TypeData>(); int len = blocks.length; int index = 0; for (int i = 0; i < len; i++) { @@ -522,8 +530,7 @@ public class MapMaker extends Tracer { return diffSize(newTd, len, newTdLen); else return -diffSize(oldTd, len, oldTdLen); - else - return -100; + return -100; } private static boolean stackMapEq(TypeData[] oldTd, TypeData[] newTd, int len) { diff --git a/src/main/javassist/bytecode/stackmap/Tracer.java b/src/main/javassist/bytecode/stackmap/Tracer.java index 182935e6..6f99e5f7 100644 --- a/src/main/javassist/bytecode/stackmap/Tracer.java +++ b/src/main/javassist/bytecode/stackmap/Tracer.java @@ -16,12 +16,12 @@ package javassist.bytecode.stackmap; +import javassist.ClassPool; +import javassist.bytecode.BadBytecode; import javassist.bytecode.ByteArray; -import javassist.bytecode.Opcode; import javassist.bytecode.ConstPool; import javassist.bytecode.Descriptor; -import javassist.bytecode.BadBytecode; -import javassist.ClassPool; +import javassist.bytecode.Opcode; /* * A class for performing abstract interpretation. @@ -69,16 +69,13 @@ public abstract class Tracer implements TypeTag { protected int doOpcode(int pos, byte[] code) throws BadBytecode { try { int op = code[pos] & 0xff; + if (op < 54) + return doOpcode0_53(pos, code, op); if (op < 96) - if (op < 54) - return doOpcode0_53(pos, code, op); - else - return doOpcode54_95(pos, code, op); - else - if (op < 148) - return doOpcode96_147(pos, code, op); - else - return doOpcode148_201(pos, code, op); + return doOpcode54_95(pos, code, op); + if (op < 148) + return doOpcode96_147(pos, code, op); + return doOpcode148_201(pos, code, op); } catch (ArrayIndexOutOfBoundsException e) { throw new BadBytecode("inconsistent stack height " + e.getMessage(), e); diff --git a/src/main/javassist/bytecode/stackmap/TypeData.java b/src/main/javassist/bytecode/stackmap/TypeData.java index 206fd52a..9bc837d3 100644 --- a/src/main/javassist/bytecode/stackmap/TypeData.java +++ b/src/main/javassist/bytecode/stackmap/TypeData.java @@ -16,16 +16,19 @@ package javassist.bytecode.stackmap; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; +import javassist.bytecode.BadBytecode; import javassist.bytecode.ConstPool; import javassist.bytecode.Descriptor; import javassist.bytecode.StackMapTable; -import javassist.bytecode.BadBytecode; -import java.util.HashSet; -import java.util.Iterator; -import java.util.ArrayList; public abstract class TypeData { /* Memo: @@ -49,6 +52,7 @@ public abstract class TypeData { * * @param className dot-separated name unless the type is an array type. */ + @SuppressWarnings("unused") private static void setType(TypeData td, String className, ClassPool cp) throws BadBytecode { td.setType(className, cp); } @@ -89,7 +93,7 @@ public abstract class TypeData { * @param order a node stack in the order in which nodes are visited. * @param index the index used by the algorithm. */ - public int dfs(ArrayList order, int index, ClassPool cp) + public int dfs(List<TypeData> order, int index, ClassPool cp) throws NotFoundException { return index; @@ -107,11 +111,12 @@ public abstract class TypeData { // see UninitTypeVar and UninitData public void constructorCalled(int offset) {} + @Override public String toString() { - return super.toString() + "(" + toString2(new HashSet()) + ")"; + return super.toString() + "(" + toString2(new HashSet<TypeData>()) + ")"; } - abstract String toString2(HashSet set); + abstract String toString2(Set<TypeData> set); /** * Primitive types. @@ -127,31 +132,38 @@ public abstract class TypeData { decodedName = decoded; } + @Override public int getTypeTag() { return typeTag; } + @Override public int getTypeData(ConstPool cp) { return 0; } + @Override public TypeData join() { if (this == TypeTag.TOP) return this; - else - return super.join(); + return super.join(); } + @Override public BasicType isBasicType() { return this; } + @Override public boolean is2WordType() { return typeTag == StackMapTable.LONG || typeTag == StackMapTable.DOUBLE; } + @Override public boolean eq(TypeData d) { return this == d; } + @Override public String getName() { return name; } public char getDecodedName() { return decodedName; } + @Override public void setType(String s, ClassPool cp) throws BadBytecode { throw new BadBytecode("conflict: " + name + " and " + s); } @@ -159,6 +171,7 @@ public abstract class TypeData { /** * @param dim array dimension. It may be negative. */ + @Override public TypeData getArrayType(int dim) throws NotFoundException { if (this == TypeTag.TOP) return this; @@ -176,103 +189,109 @@ public abstract class TypeData { } } - String toString2(HashSet set) { return name; } + @Override + String toString2(Set<TypeData> set) { return name; } } // a type variable public static abstract class AbsTypeVar extends TypeData { public AbsTypeVar() {} public abstract void merge(TypeData t); + @Override public int getTypeTag() { return StackMapTable.OBJECT; } + @Override public int getTypeData(ConstPool cp) { return cp.addClassInfo(getName()); } + @Override public boolean eq(TypeData d) { return getName().equals(d.getName()); } } /* a type variable representing a class type or a basic type. */ public static class TypeVar extends AbsTypeVar { - protected ArrayList lowers; // lower bounds of this type. ArrayList<TypeData> - protected ArrayList usedBy; // reverse relations of lowers - protected ArrayList uppers; // upper bounds of this type. + protected List<TypeData> lowers;// lower bounds of this type. ArrayList<TypeData> + protected List<TypeData> usedBy;// reverse relations of lowers + protected List<String> uppers; // upper bounds of this type. protected String fixedType; private boolean is2WordType; // cache public TypeVar(TypeData t) { uppers = null; - lowers = new ArrayList(2); - usedBy = new ArrayList(2); + lowers = new ArrayList<TypeData>(2); + usedBy = new ArrayList<TypeData>(2); merge(t); fixedType = null; is2WordType = t.is2WordType(); } + @Override public String getName() { if (fixedType == null) - return ((TypeData)lowers.get(0)).getName(); - else - return fixedType; + return lowers.get(0).getName(); + return fixedType; } + @Override public BasicType isBasicType() { if (fixedType == null) - return ((TypeData)lowers.get(0)).isBasicType(); - else - return null; + return lowers.get(0).isBasicType(); + return null; } + @Override public boolean is2WordType() { if (fixedType == null) { return is2WordType; // return ((TypeData)lowers.get(0)).is2WordType(); } - else - return false; + return false; } + @Override public boolean isNullType() { if (fixedType == null) - return ((TypeData)lowers.get(0)).isNullType(); - else - return false; + return lowers.get(0).isNullType(); + return false; } + @Override public boolean isUninit() { if (fixedType == null) - return ((TypeData)lowers.get(0)).isUninit(); - else - return false; + return lowers.get(0).isUninit(); + return false; } + @Override public void merge(TypeData t) { lowers.add(t); if (t instanceof TypeVar) ((TypeVar)t).usedBy.add(this); } + @Override public int getTypeTag() { /* If fixedType is null after calling dfs(), then this type is NULL, Uninit, or a basic type. So call getTypeTag() on the first element of lowers. */ if (fixedType == null) - return ((TypeData)lowers.get(0)).getTypeTag(); - else - return super.getTypeTag(); + return lowers.get(0).getTypeTag(); + return super.getTypeTag(); } + @Override public int getTypeData(ConstPool cp) { if (fixedType == null) - return ((TypeData)lowers.get(0)).getTypeData(cp); - else - return super.getTypeData(cp); + return lowers.get(0).getTypeData(cp); + return super.getTypeData(cp); } + @Override public void setType(String typeName, ClassPool cp) throws BadBytecode { if (uppers == null) - uppers = new ArrayList(); + uppers = new ArrayList<String>(); uppers.add(typeName); } @@ -282,6 +301,7 @@ public abstract class TypeData { private boolean inList = false; private int dimension = 0; + @Override protected TypeVar toTypeVar(int dim) { dimension = dim; return this; @@ -290,23 +310,22 @@ public abstract class TypeData { /* When fixTypes() is called, getName() will return the correct * (i.e. fixed) type name. */ + @Override public TypeData getArrayType(int dim) throws NotFoundException { if (dim == 0) return this; - else { - BasicType bt = isBasicType(); - if (bt == null) - if (isNullType()) - return new NullType(); - else - return new ClassName(getName()).getArrayType(dim); + BasicType bt = isBasicType(); + if (bt == null) + if (isNullType()) + return new NullType(); else - return bt.getArrayType(dim); - } + return new ClassName(getName()).getArrayType(dim); + return bt.getArrayType(dim); } // depth-first serach - public int dfs(ArrayList preOrder, int index, ClassPool cp) throws NotFoundException { + @Override + public int dfs(List<TypeData> preOrder, int index, ClassPool cp) throws NotFoundException { if (visited > 0) return index; // MapMaker.make() may call an already visited node. @@ -315,7 +334,7 @@ public abstract class TypeData { inList = true; int n = lowers.size(); for (int i = 0; i < n; i++) { - TypeVar child = ((TypeData)lowers.get(i)).toTypeVar(dimension); + TypeVar child = lowers.get(i).toTypeVar(dimension); if (child != null) if (child.visited == 0) { index = child.dfs(preOrder, index, cp); @@ -328,7 +347,7 @@ public abstract class TypeData { } if (visited == smallest) { - ArrayList scc = new ArrayList(); // strongly connected component + List<TypeData> scc = new ArrayList<TypeData>(); // strongly connected component TypeVar cv; do { cv = (TypeVar)preOrder.remove(preOrder.size() - 1); @@ -341,17 +360,17 @@ public abstract class TypeData { return index; } - private void fixTypes(ArrayList scc, ClassPool cp) throws NotFoundException { - HashSet lowersSet = new HashSet(); + private void fixTypes(List<TypeData> scc, ClassPool cp) throws NotFoundException { + Set<String> lowersSet = new HashSet<String>(); boolean isBasicType = false; TypeData kind = null; int size = scc.size(); for (int i = 0; i < size; i++) { TypeVar tvar = (TypeVar)scc.get(i); - ArrayList tds = tvar.lowers; + List<TypeData> tds = tvar.lowers; int size2 = tds.size(); for (int j = 0; j < size2; j++) { - TypeData td = (TypeData)tds.get(j); + TypeData td = tds.get(j); TypeData d = td.getArrayType(tvar.dimension); BasicType bt = d.isBasicType(); if (kind == null) { @@ -393,7 +412,7 @@ public abstract class TypeData { } } - private void fixTypes1(ArrayList scc, TypeData kind) throws NotFoundException { + private void fixTypes1(List<TypeData> scc, TypeData kind) throws NotFoundException { int size = scc.size(); for (int i = 0; i < size; i++) { TypeVar cv = (TypeVar)scc.get(i); @@ -408,24 +427,24 @@ public abstract class TypeData { } } - private String fixTypes2(ArrayList scc, HashSet lowersSet, ClassPool cp) throws NotFoundException { - Iterator it = lowersSet.iterator(); + private String fixTypes2(List<TypeData> scc, Set<String> lowersSet, ClassPool cp) throws NotFoundException { + Iterator<String> it = lowersSet.iterator(); if (lowersSet.size() == 0) return null; // only NullType else if (lowersSet.size() == 1) - return (String)it.next(); + return it.next(); else { - CtClass cc = cp.get((String)it.next()); + CtClass cc = cp.get(it.next()); while (it.hasNext()) - cc = commonSuperClassEx(cc, cp.get((String)it.next())); + cc = commonSuperClassEx(cc, cp.get(it.next())); if (cc.getSuperclass() == null || isObjectArray(cc)) - cc = fixByUppers(scc, cp, new HashSet(), cc); + cc = fixByUppers(scc, cp, new HashSet<TypeData>(), cc); if (cc.isArray()) return Descriptor.toJvmName(cc); - else - return cc.getName(); + + return cc.getName(); } } @@ -433,7 +452,7 @@ public abstract class TypeData { return cc.isArray() && cc.getComponentType().getSuperclass() == null; } - private CtClass fixByUppers(ArrayList users, ClassPool cp, HashSet visited, CtClass type) + private CtClass fixByUppers(List<TypeData> users, ClassPool cp, Set<TypeData> visited, CtClass type) throws NotFoundException { if (users == null) @@ -448,7 +467,7 @@ public abstract class TypeData { if (t.uppers != null) { int s = t.uppers.size(); for (int k = 0; k < s; k++) { - CtClass cc = cp.get((String)t.uppers.get(k)); + CtClass cc = cp.get(t.uppers.get(k)); if (cc.subtypeOf(type)) type = cc; } @@ -460,13 +479,13 @@ public abstract class TypeData { return type; } - String toString2(HashSet hash) { + @Override + String toString2(Set<TypeData> hash) { hash.add(this); if (lowers.size() > 0) { - TypeData e = (TypeData)lowers.get(0); - if (e != null && !hash.contains(e)) { + TypeData e = lowers.get(0); + if (e != null && !hash.contains(e)) return e.toString2(hash); - } } return "?"; @@ -494,7 +513,7 @@ public abstract class TypeData { } else if (one.isPrimitive() || two.isPrimitive()) return null; // TOP - else if (one.isArray() || two.isArray()) // but !(one.isArray() && two.isArray()) + else if (one.isArray() || two.isArray()) // but !(one.isArray() && two.isArray()) return one.getClassPool().get("java.lang.Object"); else return commonSuperClass(one, two); @@ -605,6 +624,7 @@ public abstract class TypeData { throw new BadBytecode("bad AASTORE: " + element); } + @Override public void merge(TypeData t) { try { if (!t.isNullType()) @@ -616,13 +636,16 @@ public abstract class TypeData { } } + @Override public String getName() { return typeName(element.getName()); } public AbsTypeVar elementType() { return element; } + @Override public BasicType isBasicType() { return null; } + @Override public boolean is2WordType() { return false; } /* elementType must be a class name. Basic type names @@ -631,25 +654,29 @@ public abstract class TypeData { public static String typeName(String elementType) { if (elementType.charAt(0) == '[') return "[" + elementType; - else - return "[L" + elementType.replace('.', '/') + ";"; + return "[L" + elementType.replace('.', '/') + ";"; } + @Override public void setType(String s, ClassPool cp) throws BadBytecode { element.setType(ArrayElement.typeName(s), cp); } + @Override protected TypeVar toTypeVar(int dim) { return element.toTypeVar(dim + 1); } + @Override public TypeData getArrayType(int dim) throws NotFoundException { return element.getArrayType(dim + 1); } - public int dfs(ArrayList order, int index, ClassPool cp) throws NotFoundException { + @Override + public int dfs(List<TypeData> order, int index, ClassPool cp) throws NotFoundException { return element.dfs(order, index, cp); } - String toString2(HashSet set) { + @Override + String toString2(Set<TypeData> set) { return "[" + element.toString2(set); } } @@ -659,7 +686,7 @@ public abstract class TypeData { */ public static class ArrayElement extends AbsTypeVar { private AbsTypeVar array; - + private ArrayElement(AbsTypeVar a) { // a is never null array = a; } @@ -676,6 +703,7 @@ public abstract class TypeData { throw new BadBytecode("bad AASTORE: " + array); } + @Override public void merge(TypeData t) { try { if (!t.isNullType()) @@ -687,6 +715,7 @@ public abstract class TypeData { } } + @Override public String getName() { return typeName(array.getName()); } @@ -697,8 +726,10 @@ public abstract class TypeData { * not allowed. */ + @Override public BasicType isBasicType() { return null; } + @Override public boolean is2WordType() { return false; } private static String typeName(String arrayType) { @@ -713,21 +744,26 @@ public abstract class TypeData { return "java.lang.Object"; // the array type may be NullType } + @Override public void setType(String s, ClassPool cp) throws BadBytecode { array.setType(ArrayType.typeName(s), cp); } + @Override protected TypeVar toTypeVar(int dim) { return array.toTypeVar(dim - 1); } + @Override public TypeData getArrayType(int dim) throws NotFoundException { return array.getArrayType(dim - 1); } - public int dfs(ArrayList order, int index, ClassPool cp) throws NotFoundException { + @Override + public int dfs(List<TypeData> order, int index, ClassPool cp) throws NotFoundException { return array.dfs(order, index, cp); } - String toString2(HashSet set) { + @Override + String toString2(Set<TypeData> set) { return "*" + array.toString2(set); } } @@ -736,26 +772,38 @@ public abstract class TypeData { protected TypeData type; // UninitData or TOP public UninitTypeVar(UninitData t) { type = t; } + @Override public int getTypeTag() { return type.getTypeTag(); } + @Override public int getTypeData(ConstPool cp) { return type.getTypeData(cp); } + @Override public BasicType isBasicType() { return type.isBasicType(); } + @Override public boolean is2WordType() { return type.is2WordType(); } + @Override public boolean isUninit() { return type.isUninit(); } + @Override public boolean eq(TypeData d) { return type.eq(d); } + @Override public String getName() { return type.getName(); } + @Override protected TypeVar toTypeVar(int dim) { return null; } + @Override public TypeData join() { return type.join(); } + @Override public void setType(String s, ClassPool cp) throws BadBytecode { type.setType(s, cp); } + @Override public void merge(TypeData t) { if (!t.eq(type)) type = TypeTag.TOP; } + @Override public void constructorCalled(int offset) { type.constructorCalled(offset); } @@ -763,15 +811,16 @@ public abstract class TypeData { public int offset() { if (type instanceof UninitData) return ((UninitData)type).offset; - else // if type == TypeTag.TOP - throw new RuntimeException("not available"); + throw new RuntimeException("not available"); } + @Override public TypeData getArrayType(int dim) throws NotFoundException { return type.getArrayType(dim); } - String toString2(HashSet set) { return ""; } + @Override + String toString2(Set<TypeData> set) { return ""; } } /** @@ -784,24 +833,32 @@ public abstract class TypeData { name = n; } + @Override public String getName() { return name; } + @Override public BasicType isBasicType() { return null; } + @Override public boolean is2WordType() { return false; } + @Override public int getTypeTag() { return StackMapTable.OBJECT; } + @Override public int getTypeData(ConstPool cp) { return cp.addClassInfo(getName()); } + @Override public boolean eq(TypeData d) { return name.equals(d.getName()); } + @Override public void setType(String typeName, ClassPool cp) throws BadBytecode {} + @Override public TypeData getArrayType(int dim) throws NotFoundException { if (dim == 0) return this; @@ -825,7 +882,7 @@ public abstract class TypeData { if (type == '[') return new ClassName(name.substring(-dim)); else if (type == 'L') - return new ClassName(name.substring(-dim + 1, name.length() - 1).replace('/', '.')); + return new ClassName(name.substring(-dim + 1, name.length() - 1).replace('/', '.')); else if (type == TypeTag.DOUBLE.decodedName) return TypeTag.DOUBLE; else if (type == TypeTag.FLOAT.decodedName) @@ -837,7 +894,8 @@ public abstract class TypeData { } } - String toString2(HashSet set) { + @Override + String toString2(Set<TypeData> set) { return name; } } @@ -852,13 +910,17 @@ public abstract class TypeData { super("null-type"); // type name } + @Override public int getTypeTag() { return StackMapTable.NULL; } + @Override public boolean isNullType() { return true; } + @Override public int getTypeData(ConstPool cp) { return 0; } + @Override public TypeData getArrayType(int dim) { return this; } } @@ -877,40 +939,45 @@ public abstract class TypeData { public UninitData copy() { return new UninitData(offset, getName()); } + @Override public int getTypeTag() { return StackMapTable.UNINIT; } + @Override public int getTypeData(ConstPool cp) { return offset; } + @Override public TypeData join() { if (initialized) return new TypeVar(new ClassName(getName())); - else - return new UninitTypeVar(copy()); + return new UninitTypeVar(copy()); } + @Override public boolean isUninit() { return true; } + @Override public boolean eq(TypeData d) { if (d instanceof UninitData) { UninitData ud = (UninitData)d; return offset == ud.offset && getName().equals(ud.getName()); } - else - return false; + return false; } public int offset() { return offset; } + @Override public void constructorCalled(int offset) { if (offset == this.offset) initialized = true; } - String toString2(HashSet set) { return getName() + "," + offset; } + @Override + String toString2(Set<TypeData> set) { return getName() + "," + offset; } } public static class UninitThis extends UninitData { @@ -918,16 +985,20 @@ public abstract class TypeData { super(-1, className); } + @Override public UninitData copy() { return new UninitThis(getName()); } + @Override public int getTypeTag() { return StackMapTable.THIS; } + @Override public int getTypeData(ConstPool cp) { return 0; } - String toString2(HashSet set) { return "uninit:this"; } + @Override + String toString2(Set<TypeData> set) { return "uninit:this"; } } } diff --git a/src/main/javassist/bytecode/stackmap/TypedBlock.java b/src/main/javassist/bytecode/stackmap/TypedBlock.java index 719ad67f..14fa7f22 100644 --- a/src/main/javassist/bytecode/stackmap/TypedBlock.java +++ b/src/main/javassist/bytecode/stackmap/TypedBlock.java @@ -16,7 +16,11 @@ package javassist.bytecode.stackmap; -import javassist.bytecode.*; +import javassist.bytecode.AccessFlag; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.ConstPool; +import javassist.bytecode.MethodInfo; public class TypedBlock extends BasicBlock { public int stackTop, numLocals; @@ -54,6 +58,7 @@ public class TypedBlock extends BasicBlock { localsTypes = null; } + @Override protected void toString2(StringBuffer sbuf) { super.toString2(sbuf); sbuf.append(",\n stack={"); @@ -110,10 +115,12 @@ public class TypedBlock extends BasicBlock { } public static class Maker extends BasicBlock.Maker { + @Override protected BasicBlock makeBlock(int pos) { return new TypedBlock(pos); } + @Override protected BasicBlock[] makeArray(int size) { return new TypedBlock[size]; } diff --git a/src/main/javassist/compiler/AccessorMaker.java b/src/main/javassist/compiler/AccessorMaker.java index 05d19ed1..02030c1b 100644 --- a/src/main/javassist/compiler/AccessorMaker.java +++ b/src/main/javassist/compiler/AccessorMaker.java @@ -16,9 +16,22 @@ package javassist.compiler; -import javassist.*; -import javassist.bytecode.*; import java.util.HashMap; +import java.util.Map; + +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.NotFoundException; +import javassist.bytecode.AccessFlag; +import javassist.bytecode.Bytecode; +import javassist.bytecode.ClassFile; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.ExceptionsAttribute; +import javassist.bytecode.FieldInfo; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.SyntheticAttribute; /** * AccessorMaker maintains accessors to private members of an enclosing @@ -27,14 +40,14 @@ import java.util.HashMap; public class AccessorMaker { private CtClass clazz; private int uniqueNumber; - private HashMap accessors; + private Map<String,Object> accessors; static final String lastParamType = "javassist.runtime.Inner"; public AccessorMaker(CtClass c) { clazz = c; uniqueNumber = 1; - accessors = new HashMap(); + accessors = new HashMap<String,Object>(); } public String getConstructor(CtClass c, String desc, MethodInfo orig) diff --git a/src/main/javassist/compiler/CodeGen.java b/src/main/javassist/compiler/CodeGen.java index ab02d8cf..d4c748f8 100644 --- a/src/main/javassist/compiler/CodeGen.java +++ b/src/main/javassist/compiler/CodeGen.java @@ -18,10 +18,36 @@ package javassist.compiler; import java.util.ArrayList; import java.util.Arrays; -import javassist.compiler.ast.*; -import javassist.bytecode.*; - -/* The code generator is implemeted by three files: +import java.util.List; + +import javassist.bytecode.Bytecode; +import javassist.bytecode.Opcode; +import javassist.compiler.ast.ASTList; +import javassist.compiler.ast.ASTree; +import javassist.compiler.ast.ArrayInit; +import javassist.compiler.ast.AssignExpr; +import javassist.compiler.ast.BinExpr; +import javassist.compiler.ast.CallExpr; +import javassist.compiler.ast.CastExpr; +import javassist.compiler.ast.CondExpr; +import javassist.compiler.ast.Declarator; +import javassist.compiler.ast.DoubleConst; +import javassist.compiler.ast.Expr; +import javassist.compiler.ast.FieldDecl; +import javassist.compiler.ast.InstanceOfExpr; +import javassist.compiler.ast.IntConst; +import javassist.compiler.ast.Keyword; +import javassist.compiler.ast.Member; +import javassist.compiler.ast.MethodDecl; +import javassist.compiler.ast.NewExpr; +import javassist.compiler.ast.Pair; +import javassist.compiler.ast.Stmnt; +import javassist.compiler.ast.StringL; +import javassist.compiler.ast.Symbol; +import javassist.compiler.ast.Variable; +import javassist.compiler.ast.Visitor; + +/* The code generator is implemented by three files: * CodeGen.java, MemberCodeGen.java, and JvstCodeGen. * I just wanted to split a big file into three smaller ones. */ @@ -47,7 +73,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { */ public boolean inStaticMethod; - protected ArrayList breakList, continueList; + protected List<Integer> breakList, continueList; /** * doit() in ReturnHook is called from atReturn(). @@ -171,18 +197,16 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { if (dim == 0) return name; - else { - StringBuffer sbuf = new StringBuffer(); - int d = dim; - while (d-- > 0) - sbuf.append('['); + StringBuffer sbuf = new StringBuffer(); + int d = dim; + while (d-- > 0) + sbuf.append('['); - sbuf.append('L'); - sbuf.append(name); - sbuf.append(';'); + sbuf.append('L'); + sbuf.append(name); + sbuf.append(';'); - return sbuf.toString(); - } + return sbuf.toString(); } protected static String toJvmTypeName(int type, int dim) { @@ -242,16 +266,21 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { expr.accept(typeChecker); } + @Override public void atASTList(ASTList n) throws CompileError { fatal(); } - + + @Override public void atPair(Pair n) throws CompileError { fatal(); } + @Override public void atSymbol(Symbol n) throws CompileError { fatal(); } + @Override public void atFieldDecl(FieldDecl field) throws CompileError { field.getInit().accept(this); } + @Override public void atMethodDecl(MethodDecl method) throws CompileError { ASTList mods = method.getModifiers(); setMaxLocals(1); @@ -263,7 +292,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { inStaticMethod = true; } } - + ASTList params = method.getParams(); while (params != null) { atDeclarator((Declarator)params.head()); @@ -320,6 +349,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { protected abstract void insertDefaultSuperCall() throws CompileError; + @Override public void atStmnt(Stmnt st) throws CompileError { if (st == null) return; // empty @@ -417,10 +447,10 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { } private void atWhileStmnt(Stmnt st, boolean notDo) throws CompileError { - ArrayList prevBreakList = breakList; - ArrayList prevContList = continueList; - breakList = new ArrayList(); - continueList = new ArrayList(); + List<Integer> prevBreakList = breakList; + List<Integer> prevContList = continueList; + breakList = new ArrayList<Integer>(); + continueList = new ArrayList<Integer>(); ASTree expr = st.head(); Stmnt body = (Stmnt)st.tail(); @@ -454,19 +484,16 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { hasReturned = alwaysBranch; } - protected void patchGoto(ArrayList list, int targetPc) { - int n = list.size(); - for (int i = 0; i < n; ++i) { - int pc = ((Integer)list.get(i)).intValue(); + protected void patchGoto(List<Integer> list, int targetPc) { + for (int pc:list) bytecode.write16bit(pc, targetPc - pc + 1); - } } private void atForStmnt(Stmnt st) throws CompileError { - ArrayList prevBreakList = breakList; - ArrayList prevContList = continueList; - breakList = new ArrayList(); - continueList = new ArrayList(); + List<Integer> prevBreakList = breakList; + List<Integer> prevContList = continueList; + breakList = new ArrayList<Integer>(); + continueList = new ArrayList<Integer>(); Stmnt init = (Stmnt)st.head(); ASTList p = st.tail(); @@ -517,8 +544,8 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { private void atSwitchStmnt(Stmnt st) throws CompileError { compileExpr(st.head()); - ArrayList prevBreakList = breakList; - breakList = new ArrayList(); + List<Integer> prevBreakList = breakList; + breakList = new ArrayList<Integer>(); int opcodePc = bytecode.currentPc(); bytecode.addOpcode(LOOKUPSWITCH); int npads = 3 - (opcodePc & 3); @@ -583,8 +610,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { expr = TypeChecker.stripPlusExpr(expr); if (expr instanceof IntConst) return (int)((IntConst)expr).get(); - else - throw new CompileError("bad case label"); + throw new CompileError("bad case label"); } private void atBreakStmnt(Stmnt st, boolean notCont) @@ -672,6 +698,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { bc.addOpcode(MONITORENTER); ReturnHook rh = new ReturnHook(this) { + @Override protected boolean doit(Bytecode b, int opcode) { b.addAload(var); b.addOpcode(MONITOREXIT); @@ -711,7 +738,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { "sorry, cannot break/continue in synchronized block"); } - private static int getListSize(ArrayList list) { + private static int getListSize(List<Integer> list) { return list == null ? 0 : list.size(); } @@ -724,6 +751,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { return false; } + @Override public void atDeclarator(Declarator d) throws CompileError { d.setLocalVar(getMaxLocals()); d.setClassName(resolveClassName(d.getClassName())); @@ -745,10 +773,13 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { } } + @Override public abstract void atNewExpr(NewExpr n) throws CompileError; + @Override public abstract void atArrayInit(ArrayInit init) throws CompileError; + @Override public void atAssignExpr(AssignExpr expr) throws CompileError { atAssignExpr(expr, true); } @@ -931,6 +962,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { return false; } + @Override public void atCondExpr(CondExpr expr) throws CompileError { if (booleanExpr(false, expr.condExpr())) expr.elseExpr().accept(this); @@ -974,6 +1006,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { return -1; } + @Override public void atBinExpr(BinExpr expr) throws CompileError { int token = expr.getOperator(); @@ -1136,7 +1169,6 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { arrayDim = 0; return true; } - else { int pc = bytecode.currentPc(); bytecode.addIndex(0); // correct later if (booleanExpr(isAndAnd, bexpr.oprand2())) @@ -1147,7 +1179,6 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { bytecode.addIndex(6); // skip GOTO instruction bytecode.addOpcode(Opcode.GOTO); } - } } else if (isAlwaysBranch(expr, branchIf)) { // Opcode.GOTO is not added here. The caller must add it. @@ -1207,8 +1238,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { if (type1 == NULL) return exprType; - else - return type1; + return type1; } private static final int ifOp[] = { EQ, IF_ICMPEQ, IF_ICMPNE, @@ -1390,6 +1420,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { bytecode.addOpcode(op); } + @Override public void atCastExpr(CastExpr expr) throws CompileError { String cname = resolveClassName(expr.getClassName()); String toClass = checkCastExpr(expr, cname); @@ -1403,6 +1434,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { bytecode.addCheckcast(toClass); } + @Override public void atInstanceOfExpr(InstanceOfExpr expr) throws CompileError { String cname = resolveClassName(expr.getClassName()); String toClass = checkCastExpr(expr, cname); @@ -1443,7 +1475,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { { if (srcType == destType) return; - + int op, op2; int stype = typePrecedence(srcType); int dtype = typePrecedence(destType); @@ -1475,6 +1507,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { bytecode.addOpcode(op2); } + @Override public void atExpr(Expr expr) throws CompileError { // array access, member access, // (unary) +, (unary) -, ++, --, !, ~ @@ -1483,7 +1516,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { ASTree oprand = expr.oprand1(); if (token == '.') { String member = ((Symbol)expr.oprand2()).get(); - if (member.equals("class")) + if (member.equals("class")) atClassObject(expr); // .class else atFieldRead(expr); @@ -1560,6 +1593,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { throw new CompileError("invalid type for " + expr.getName()); } + @Override public abstract void atCallExpr(CallExpr expr) throws CompileError; protected abstract void atFieldRead(ASTree expr) throws CompileError; @@ -1749,7 +1783,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { if (doDup && isPost) bytecode.addOpcode(DUP2); - bytecode.addLconst((long)1); + bytecode.addLconst(1); bytecode.addOpcode(token == PLUSPLUS ? LADD : LSUB); if (doDup && !isPost) bytecode.addOpcode(DUP2); @@ -1835,7 +1869,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { exprType = INT; } else if (t == LONG) { - bytecode.addLconst((long)1); + bytecode.addLconst(1); bytecode.addOpcode(token == PLUSPLUS ? LADD : LSUB); } else if (t == FLOAT) { @@ -1856,8 +1890,10 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { protected abstract void atFieldPlusPlus(int token, boolean isPost, ASTree oprand, Expr expr, boolean doDup) throws CompileError; + @Override public abstract void atMember(Member n) throws CompileError; + @Override public void atVariable(Variable v) throws CompileError { Declarator d = v.getDeclarator(); exprType = d.getType(); @@ -1887,6 +1923,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { } } + @Override public void atKeyword(Keyword k) throws CompileError { arrayDim = 0; int token = k.get(); @@ -1914,13 +1951,14 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { if (token == THIS) className = getThisName(); else - className = getSuperName(); + className = getSuperName(); break; default : fatal(); } } + @Override public void atStringL(StringL s) throws CompileError { exprType = CLASS; arrayDim = 0; @@ -1928,6 +1966,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { bytecode.addLdc(s.get()); } + @Override public void atIntConst(IntConst i) throws CompileError { arrayDim = 0; long value = i.get(); @@ -1942,6 +1981,7 @@ public abstract class CodeGen extends Visitor implements Opcode, TokenId { } } + @Override public void atDoubleConst(DoubleConst d) throws CompileError { arrayDim = 0; if (d.getType() == DoubleConstant) { diff --git a/src/main/javassist/compiler/CompileError.java b/src/main/javassist/compiler/CompileError.java index 331b7847..5b857cf2 100644 --- a/src/main/javassist/compiler/CompileError.java +++ b/src/main/javassist/compiler/CompileError.java @@ -20,6 +20,8 @@ import javassist.CannotCompileException; import javassist.NotFoundException; public class CompileError extends Exception { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private Lex lex; private String reason; @@ -43,10 +45,12 @@ public class CompileError extends Exception { public Lex getLex() { return lex; } + @Override public String getMessage() { return reason; } + @Override public String toString() { return "compile error: " + reason; } diff --git a/src/main/javassist/compiler/Javac.java b/src/main/javassist/compiler/Javac.java index fc3d803f..084487b4 100644 --- a/src/main/javassist/compiler/Javac.java +++ b/src/main/javassist/compiler/Javac.java @@ -16,23 +16,31 @@ package javassist.compiler; +import javassist.CannotCompileException; +import javassist.CtBehavior; import javassist.CtClass; -import javassist.CtPrimitiveType; -import javassist.CtMember; +import javassist.CtConstructor; import javassist.CtField; -import javassist.CtBehavior; +import javassist.CtMember; import javassist.CtMethod; -import javassist.CtConstructor; -import javassist.CannotCompileException; +import javassist.CtPrimitiveType; import javassist.Modifier; +import javassist.NotFoundException; +import javassist.bytecode.BadBytecode; import javassist.bytecode.Bytecode; import javassist.bytecode.CodeAttribute; import javassist.bytecode.LocalVariableAttribute; -import javassist.bytecode.BadBytecode; import javassist.bytecode.Opcode; -import javassist.NotFoundException; - -import javassist.compiler.ast.*; +import javassist.compiler.ast.ASTList; +import javassist.compiler.ast.ASTree; +import javassist.compiler.ast.CallExpr; +import javassist.compiler.ast.Declarator; +import javassist.compiler.ast.Expr; +import javassist.compiler.ast.FieldDecl; +import javassist.compiler.ast.Member; +import javassist.compiler.ast.MethodDecl; +import javassist.compiler.ast.Stmnt; +import javassist.compiler.ast.Symbol; public class Javac { JvstCodeGen gen; @@ -91,14 +99,12 @@ public class Javac { try { if (mem instanceof FieldDecl) return compileField((FieldDecl)mem); - else { - CtBehavior cb = compileMethod(p, (MethodDecl)mem); - CtClass decl = cb.getDeclaringClass(); - cb.getMethodInfo2() - .rebuildStackMapIf6(decl.getClassPool(), - decl.getClassFile2()); - return cb; - } + CtBehavior cb = compileMethod(p, (MethodDecl)mem); + CtClass decl = cb.getDeclaringClass(); + cb.getMethodInfo2() + .rebuildStackMapIf6(decl.getClassPool(), + decl.getClassFile2()); + return cb; } catch (BadBytecode bb) { throw new CompileError(bb.getMessage()); @@ -120,6 +126,7 @@ public class Javac { protected void setInit(ASTree i) { init = i; } + @Override protected ASTree getInitAST() { return init; } @@ -158,24 +165,22 @@ public class Javac { cons.setExceptionTypes(tlist); return cons; } - else { - Declarator r = md.getReturn(); - CtClass rtype = gen.resolver.lookupClass(r); - recordReturnType(rtype, false); - CtMethod method = new CtMethod(rtype, r.getVariable().get(), - plist, gen.getThisClass()); - method.setModifiers(mod); - gen.setThisMethod(method); - md.accept(gen); - if (md.getBody() != null) - method.getMethodInfo().setCodeAttribute( - bytecode.toCodeAttribute()); - else - method.setModifiers(mod | Modifier.ABSTRACT); + Declarator r = md.getReturn(); + CtClass rtype = gen.resolver.lookupClass(r); + recordReturnType(rtype, false); + CtMethod method = new CtMethod(rtype, r.getVariable().get(), + plist, gen.getThisClass()); + method.setModifiers(mod); + gen.setThisMethod(method); + md.accept(gen); + if (md.getBody() != null) + method.getMethodInfo().setCodeAttribute( + bytecode.toCodeAttribute()); + else + method.setModifiers(mod | Modifier.ABSTRACT); - method.setExceptionTypes(tlist); - return method; - } + method.setExceptionTypes(tlist); + return method; } catch (NotFoundException e) { throw new CompileError(e.toString()); @@ -437,6 +442,7 @@ public class Javac { final String m = method; ProceedHandler h = new ProceedHandler() { + @Override public void doit(JvstCodeGen gen, Bytecode b, ASTList args) throws CompileError { @@ -449,6 +455,7 @@ public class Javac { gen.addNullIfVoid(); } + @Override public void setReturnType(JvstTypeChecker check, ASTList args) throws CompileError { @@ -481,6 +488,7 @@ public class Javac { final String m = method; ProceedHandler h = new ProceedHandler() { + @Override public void doit(JvstCodeGen gen, Bytecode b, ASTList args) throws CompileError { @@ -491,6 +499,7 @@ public class Javac { gen.addNullIfVoid(); } + @Override public void setReturnType(JvstTypeChecker check, ASTList args) throws CompileError { @@ -525,12 +534,14 @@ public class Javac { final ASTree texpr = p.parseExpression(stable); ProceedHandler h = new ProceedHandler() { + @Override public void doit(JvstCodeGen gen, Bytecode b, ASTList args) throws CompileError { gen.compileInvokeSpecial(texpr, methodIndex, descriptor, args); } + @Override public void setReturnType(JvstTypeChecker c, ASTList args) throws CompileError { diff --git a/src/main/javassist/compiler/JvstCodeGen.java b/src/main/javassist/compiler/JvstCodeGen.java index 797db0ce..5a43d65e 100644 --- a/src/main/javassist/compiler/JvstCodeGen.java +++ b/src/main/javassist/compiler/JvstCodeGen.java @@ -16,9 +16,21 @@ package javassist.compiler; -import javassist.*; -import javassist.bytecode.*; -import javassist.compiler.ast.*; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtPrimitiveType; +import javassist.NotFoundException; +import javassist.bytecode.Bytecode; +import javassist.bytecode.Descriptor; +import javassist.compiler.ast.ASTList; +import javassist.compiler.ast.ASTree; +import javassist.compiler.ast.CallExpr; +import javassist.compiler.ast.CastExpr; +import javassist.compiler.ast.Declarator; +import javassist.compiler.ast.Expr; +import javassist.compiler.ast.Member; +import javassist.compiler.ast.Stmnt; +import javassist.compiler.ast.Symbol; /* Code generator accepting extended Java syntax for Javassist. */ @@ -36,6 +48,7 @@ public class JvstCodeGen extends MemberCodeGen { private CtClass dollarType = null; CtClass returnType = null; String returnCastName = null; + @SuppressWarnings("unused") private String returnVarName = null; // null if $_ is not used. public static final String wrapperCastName = "$w"; String proceedName = null; @@ -78,6 +91,7 @@ public class JvstCodeGen extends MemberCodeGen { /* To support $args, $sig, and $type. * $args is an array of parameter list. */ + @Override public void atMember(Member mem) throws CompileError { String name = mem.get(); if (name.equals(paramArrayName)) { @@ -120,6 +134,7 @@ public class JvstCodeGen extends MemberCodeGen { className = "java/lang/Class"; } + @Override protected void atFieldAssign(Expr expr, int op, ASTree left, ASTree right, boolean doDup) throws CompileError { @@ -158,6 +173,7 @@ public class JvstCodeGen extends MemberCodeGen { } } + @Override public void atCastExpr(CastExpr expr) throws CompileError { ASTList classname = expr.getClassName(); if (classname != null && expr.getArrayDim() == 0) { @@ -227,6 +243,7 @@ public class JvstCodeGen extends MemberCodeGen { /* Delegates to a ProcHandler object if the method call is * $proceed(). It may process $cflow(). */ + @Override public void atCallExpr(CallExpr expr) throws CompileError { ASTree method = expr.oprand1(); if (method instanceof Member) { @@ -301,8 +318,7 @@ public class JvstCodeGen extends MemberCodeGen { return (left instanceof Member && ((Member)left).get().equals(paramListName)); } - else - return false; + return false; } /* @@ -314,6 +330,7 @@ public class JvstCodeGen extends MemberCodeGen { } */ + @Override public int getMethodArgsLength(ASTList args) { String pname = paramListName; int n = 0; @@ -332,6 +349,7 @@ public class JvstCodeGen extends MemberCodeGen { return n; } + @Override public void atMethodArgs(ASTList args, int[] types, int[] dims, String[] cnames) throws CompileError { CtClass[] params = paramTypeList; @@ -409,6 +427,7 @@ public class JvstCodeGen extends MemberCodeGen { /* * Makes it valid to write "return <expr>;" for a void method. */ + @Override protected void atReturnStmnt(Stmnt st) throws CompileError { ASTree result = st.getLeft(); if (result != null && returnType == CtClass.voidType) { @@ -442,12 +461,10 @@ public class JvstCodeGen extends MemberCodeGen { returnVarName = resultName; if (resultName == null) return -1; - else { - int varNo = getMaxLocals(); - int locals = varNo + recordVar(type, resultName, varNo, tbl); - setMaxLocals(locals); - return varNo; - } + int varNo = getMaxLocals(); + int locals = varNo + recordVar(type, resultName, varNo, tbl); + setMaxLocals(locals); + return varNo; } /** @@ -537,12 +554,10 @@ public class JvstCodeGen extends MemberCodeGen { { if (varName == null) return -1; - else { - int varNo = getMaxLocals(); - int locals = varNo + recordVar(type, varName, varNo, tbl); - setMaxLocals(locals); - return varNo; - } + int varNo = getMaxLocals(); + int locals = varNo + recordVar(type, varName, varNo, tbl); + setMaxLocals(locals); + return varNo; } private int recordVar(CtClass cc, String varName, int varNo, @@ -608,36 +623,34 @@ public class JvstCodeGen extends MemberCodeGen { code.addAnewarray(javaLangObject); // anewarray Object return 1; } - else { - CtClass[] args = new CtClass[1]; - int n = params.length; - code.addIconst(n); // iconst_<n> - code.addAnewarray(javaLangObject); // anewarray Object - for (int i = 0; i < n; ++i) { - code.addOpcode(Bytecode.DUP); // dup - code.addIconst(i); // iconst_<i> - if (params[i].isPrimitive()) { - CtPrimitiveType pt = (CtPrimitiveType)params[i]; - String wrapper = pt.getWrapperName(); - code.addNew(wrapper); // new <wrapper> - code.addOpcode(Bytecode.DUP); // dup - int s = code.addLoad(regno, pt); // ?load <regno> - regno += s; - args[0] = pt; - code.addInvokespecial(wrapper, "<init>", - Descriptor.ofMethod(CtClass.voidType, args)); - // invokespecial - } - else { - code.addAload(regno); // aload <regno> - ++regno; - } - - code.addOpcode(Bytecode.AASTORE); // aastore + CtClass[] args = new CtClass[1]; + int n = params.length; + code.addIconst(n); // iconst_<n> + code.addAnewarray(javaLangObject); // anewarray Object + for (int i = 0; i < n; ++i) { + code.addOpcode(Bytecode.DUP); // dup + code.addIconst(i); // iconst_<i> + if (params[i].isPrimitive()) { + CtPrimitiveType pt = (CtPrimitiveType)params[i]; + String wrapper = pt.getWrapperName(); + code.addNew(wrapper); // new <wrapper> + code.addOpcode(Bytecode.DUP); // dup + int s = code.addLoad(regno, pt); // ?load <regno> + regno += s; + args[0] = pt; + code.addInvokespecial(wrapper, "<init>", + Descriptor.ofMethod(CtClass.voidType, args)); + // invokespecial + } + else { + code.addAload(regno); // aload <regno> + ++regno; } - return 8; + code.addOpcode(Bytecode.AASTORE); // aastore } + + return 8; } protected void compileUnwrapValue(CtClass type, Bytecode code) diff --git a/src/main/javassist/compiler/JvstTypeChecker.java b/src/main/javassist/compiler/JvstTypeChecker.java index 9619890e..13e47291 100644 --- a/src/main/javassist/compiler/JvstTypeChecker.java +++ b/src/main/javassist/compiler/JvstTypeChecker.java @@ -16,8 +16,17 @@ package javassist.compiler; -import javassist.*; -import javassist.compiler.ast.*; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtPrimitiveType; +import javassist.NotFoundException; +import javassist.compiler.ast.ASTList; +import javassist.compiler.ast.ASTree; +import javassist.compiler.ast.CallExpr; +import javassist.compiler.ast.CastExpr; +import javassist.compiler.ast.Expr; +import javassist.compiler.ast.Member; +import javassist.compiler.ast.Symbol; /* Type checker accepting extended Java syntax for Javassist. */ @@ -44,6 +53,7 @@ public class JvstTypeChecker extends TypeChecker { /* To support $args, $sig, and $type. * $args is an array of parameter list. */ + @Override public void atMember(Member mem) throws CompileError { String name = mem.get(); if (name.equals(codeGen.paramArrayName)) { @@ -66,6 +76,7 @@ public class JvstTypeChecker extends TypeChecker { super.atMember(mem); } + @Override protected void atFieldAssign(Expr expr, int op, ASTree left, ASTree right) throws CompileError { @@ -84,6 +95,7 @@ public class JvstTypeChecker extends TypeChecker { super.atFieldAssign(expr, op, left, right); } + @Override public void atCastExpr(CastExpr expr) throws CompileError { ASTList classname = expr.getClassName(); if (classname != null && expr.getArrayDim() == 0) { @@ -138,6 +150,7 @@ public class JvstTypeChecker extends TypeChecker { /* Delegates to a ProcHandler object if the method call is * $proceed(). It may process $cflow(). */ + @Override public void atCallExpr(CallExpr expr) throws CompileError { ASTree method = expr.oprand1(); if (method instanceof Member) { @@ -175,10 +188,10 @@ public class JvstTypeChecker extends TypeChecker { return (left instanceof Member && ((Member)left).get().equals(codeGen.paramListName)); } - else - return false; + return false; } + @Override public int getMethodArgsLength(ASTList args) { String pname = codeGen.paramListName; int n = 0; @@ -197,6 +210,7 @@ public class JvstTypeChecker extends TypeChecker { return n; } + @Override public void atMethodArgs(ASTList args, int[] types, int[] dims, String[] cnames) throws CompileError { CtClass[] params = codeGen.paramTypeList; diff --git a/src/main/javassist/compiler/KeywordTable.java b/src/main/javassist/compiler/KeywordTable.java index 5f516e3d..65137d9b 100644 --- a/src/main/javassist/compiler/KeywordTable.java +++ b/src/main/javassist/compiler/KeywordTable.java @@ -16,18 +16,19 @@ package javassist.compiler; -public final class KeywordTable extends java.util.HashMap { +import java.util.HashMap; + +public final class KeywordTable extends HashMap<String,Integer> { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public KeywordTable() { super(); } public int lookup(String name) { - Object found = get(name); - if (found == null) - return -1; - else - return ((Integer)found).intValue(); + return containsKey(name) ? get(name) : -1; } public void append(String name, int t) { - put(name, Integer.valueOf(t)); + put(name, t); } } diff --git a/src/main/javassist/compiler/Lex.java b/src/main/javassist/compiler/Lex.java index eebb856e..498b22fb 100644 --- a/src/main/javassist/compiler/Lex.java +++ b/src/main/javassist/compiler/Lex.java @@ -32,6 +32,7 @@ public class Lex implements TokenId { private Token lookAheadTokens; private String input; + @SuppressWarnings("unused") private int position, maxlen, lineNumber; /** @@ -52,12 +53,10 @@ public class Lex implements TokenId { public int get() { if (lookAheadTokens == null) return get(currentToken); - else { - Token t; - currentToken = t = lookAheadTokens; - lookAheadTokens = lookAheadTokens.next; - return t.tokenId; - } + Token t; + currentToken = t = lookAheadTokens; + lookAheadTokens = lookAheadTokens.next; + return t.tokenId; } /** @@ -129,15 +128,12 @@ public class Lex implements TokenId { tbuf.append('.'); return readDouble(tbuf, c, token); } - else{ - ungetc(c); - return readSeparator('.'); - } + ungetc(c); + return readSeparator('.'); } else if (Character.isJavaIdentifierStart((char)c)) return readIdentifier(c, token); - else - return readSeparator(c); + return readSeparator(c); } private int getNextNonWhiteChar() { @@ -249,19 +245,17 @@ public class Lex implements TokenId { for (;;) { c = getc(); if ('0' <= c && c <= '9') - value = value * 16 + (long)(c - '0'); + value = value * 16 + (c - '0'); else if ('A' <= c && c <= 'F') - value = value * 16 + (long)(c - 'A' + 10); + value = value * 16 + (c - 'A' + 10); else if ('a' <= c && c <= 'f') - value = value * 16 + (long)(c - 'a' + 10); + value = value * 16 + (c - 'a' + 10); else { token.longValue = value; if (c == 'L' || c == 'l') return LongConstant; - else { - ungetc(c); - return IntConstant; - } + ungetc(c); + return IntConstant; } } else if ('0' <= c2 && c2 <= '7') { @@ -269,15 +263,13 @@ public class Lex implements TokenId { for (;;) { c = getc(); if ('0' <= c && c <= '7') - value = value * 8 + (long)(c - '0'); + value = value * 8 + (c - '0'); else { token.longValue = value; if (c == 'L' || c == 'l') return LongConstant; - else { - ungetc(c); - return IntConstant; - } + ungetc(c); + return IntConstant; } } } @@ -290,7 +282,7 @@ public class Lex implements TokenId { token.longValue = value; if (c2 == 'F' || c2 == 'f') { - token.doubleValue = (double)value; + token.doubleValue = value; return FloatConstant; } else if (c2 == 'E' || c2 == 'e' @@ -343,12 +335,10 @@ public class Lex implements TokenId { if (c == 'F' || c == 'f') return FloatConstant; - else { - if (c != 'D' && c != 'd') - ungetc(c); + if (c != 'D' && c != 'd') + ungetc(c); - return DoubleConstant; - } + return DoubleConstant; } // !"#$%&'( )*+,-./0 12345678 9:;<=>? @@ -362,51 +352,45 @@ public class Lex implements TokenId { int c2, c3; if ('!' <= c && c <= '?') { int t = equalOps[c - '!']; - if (t == 0) + if (t == 0) return c; - else { - c2 = getc(); - if (c == c2) - switch (c) { - case '=' : - return EQ; - case '+' : - return PLUSPLUS; - case '-' : - return MINUSMINUS; - case '&' : - return ANDAND; - case '<' : - c3 = getc(); - if (c3 == '=') - return LSHIFT_E; - else { - ungetc(c3); - return LSHIFT; - } - case '>' : + c2 = getc(); + if (c == c2) + switch (c) { + case '=' : + return EQ; + case '+' : + return PLUSPLUS; + case '-' : + return MINUSMINUS; + case '&' : + return ANDAND; + case '<' : + c3 = getc(); + if (c3 == '=') + return LSHIFT_E; + ungetc(c3); + return LSHIFT; + case '>' : + c3 = getc(); + if (c3 == '=') + return RSHIFT_E; + else if (c3 == '>') { c3 = getc(); if (c3 == '=') - return RSHIFT_E; - else if (c3 == '>') { - c3 = getc(); - if (c3 == '=') - return ARSHIFT_E; - else { - ungetc(c3); - return ARSHIFT; - } - } - else { - ungetc(c3); - return RSHIFT; - } - default : - break; + return ARSHIFT_E; + ungetc(c3); + return ARSHIFT; } - else if (c2 == '=') - return t; - } + else { + ungetc(c3); + return RSHIFT; + } + default : + break; + } + else if (c2 == '=') + return t; } else if (c == '^') { c2 = getc(); @@ -442,17 +426,15 @@ public class Lex implements TokenId { int t = ktable.lookup(name); if (t >= 0) return t; - else { - /* tbuf.toString() is executed quickly since it does not - * need memory copy. Using a hand-written extensible - * byte-array class instead of StringBuffer is not a good idea - * for execution speed. Converting a byte array to a String - * object is very slow. Using an extensible char array - * might be OK. - */ - token.textValue = name; - return Identifier; - } + /* tbuf.toString() is executed quickly since it does not + * need memory copy. Using a hand-written extensible + * byte-array class instead of StringBuffer is not a good idea + * for execution speed. Converting a byte array to a String + * object is very slow. Using an extensible char array + * might be OK. + */ + token.textValue = name; + return Identifier; } private static final KeywordTable ktable = new KeywordTable(); @@ -516,6 +498,7 @@ public class Lex implements TokenId { || c == '\n'; } + @SuppressWarnings("unused") private static boolean isDigit(int c) { return '0' <= c && c <= '9'; } @@ -542,10 +525,8 @@ public class Lex implements TokenId { return input.charAt(position++); else return -1; - else { - int c = lastChar; - lastChar = -1; - return c; - } + int c = lastChar; + lastChar = -1; + return c; } } diff --git a/src/main/javassist/compiler/MemberCodeGen.java b/src/main/javassist/compiler/MemberCodeGen.java index 07c113a3..ad254816 100644 --- a/src/main/javassist/compiler/MemberCodeGen.java +++ b/src/main/javassist/compiler/MemberCodeGen.java @@ -16,11 +16,36 @@ package javassist.compiler; -import javassist.*; -import javassist.bytecode.*; -import javassist.compiler.ast.*; - import java.util.ArrayList; +import java.util.List; + +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtField; +import javassist.CtMethod; +import javassist.Modifier; +import javassist.NotFoundException; +import javassist.bytecode.AccessFlag; +import javassist.bytecode.Bytecode; +import javassist.bytecode.ClassFile; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.FieldInfo; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; +import javassist.compiler.ast.ASTList; +import javassist.compiler.ast.ASTree; +import javassist.compiler.ast.ArrayInit; +import javassist.compiler.ast.CallExpr; +import javassist.compiler.ast.Declarator; +import javassist.compiler.ast.Expr; +import javassist.compiler.ast.Keyword; +import javassist.compiler.ast.Member; +import javassist.compiler.ast.MethodDecl; +import javassist.compiler.ast.NewExpr; +import javassist.compiler.ast.Pair; +import javassist.compiler.ast.Stmnt; +import javassist.compiler.ast.Symbol; /* Code generator methods depending on javassist.* classes. */ @@ -46,8 +71,7 @@ public class MemberCodeGen extends CodeGen { ClassFile cf = thisClass.getClassFile2(); if (cf == null) return ClassFile.MAJOR_VERSION; // JDK 1.3 - else - return cf.getMajorVersion(); + return cf.getMajorVersion(); } /** @@ -64,6 +88,7 @@ public class MemberCodeGen extends CodeGen { /** * Returns the JVM-internal representation of this class name. */ + @Override protected String getThisName() { return MemberResolver.javaToJvmName(thisClass.getName()); } @@ -71,11 +96,13 @@ public class MemberCodeGen extends CodeGen { /** * Returns the JVM-internal representation of this super class name. */ + @Override protected String getSuperName() throws CompileError { return MemberResolver.javaToJvmName( MemberResolver.getSuperclass(thisClass).getName()); } + @Override protected void insertDefaultSuperCall() throws CompileError { bytecode.addAload(0); bytecode.addInvokespecial(MemberResolver.getSuperclass(thisClass), @@ -83,13 +110,13 @@ public class MemberCodeGen extends CodeGen { } static class JsrHook extends ReturnHook { - ArrayList jsrList; + List<int[]> jsrList; CodeGen cgen; int var; JsrHook(CodeGen gen) { super(gen); - jsrList = new ArrayList(); + jsrList = new ArrayList<int[]>(); cgen = gen; var = -1; } @@ -109,6 +136,7 @@ public class MemberCodeGen extends CodeGen { b.addIndex(0); } + @Override protected boolean doit(Bytecode b, int opcode) { switch (opcode) { case Opcode.RETURN : @@ -157,6 +185,7 @@ public class MemberCodeGen extends CodeGen { var = retTarget[1]; } + @Override protected boolean doit(Bytecode b, int opcode) { switch (opcode) { case Opcode.RETURN : @@ -186,6 +215,7 @@ public class MemberCodeGen extends CodeGen { } } + @Override protected void atTryStmnt(Stmnt st) throws CompileError { Bytecode bc = bytecode; Stmnt body = (Stmnt)st.getLeft(); @@ -194,7 +224,7 @@ public class MemberCodeGen extends CodeGen { ASTList catchList = (ASTList)st.getRight().getLeft(); Stmnt finallyBlock = (Stmnt)st.getRight().getRight().getLeft(); - ArrayList gotoList = new ArrayList(); + List<Integer> gotoList = new ArrayList<Integer>(); JsrHook jsrHook = null; if (finallyBlock != null) @@ -209,7 +239,7 @@ public class MemberCodeGen extends CodeGen { boolean tryNotReturn = !hasReturned; if (tryNotReturn) { bc.addOpcode(Opcode.GOTO); - gotoList.add(Integer.valueOf(bc.currentPc())); + gotoList.add(bc.currentPc()); bc.addIndex(0); // correct later } @@ -235,7 +265,7 @@ public class MemberCodeGen extends CodeGen { if (!hasReturned) { bc.addOpcode(Opcode.GOTO); - gotoList.add(Integer.valueOf(bc.currentPc())); + gotoList.add(bc.currentPc()); bc.addIndex(0); // correct later tryNotReturn = true; } @@ -270,13 +300,11 @@ public class MemberCodeGen extends CodeGen { /** * Adds a finally clause for earch return statement. */ - private void addFinally(ArrayList returnList, Stmnt finallyBlock) + private void addFinally(List<int[]> returnList, Stmnt finallyBlock) throws CompileError { Bytecode bc = bytecode; - int n = returnList.size(); - for (int i = 0; i < n; ++i) { - final int[] ret = (int[])returnList.get(i); + for (final int[] ret:returnList) { int pc = ret[0]; bc.write16bit(pc, bc.currentPc() - pc + 1); ReturnHook hook = new JsrHook2(this, ret); @@ -289,6 +317,7 @@ public class MemberCodeGen extends CodeGen { } } + @Override public void atNewExpr(NewExpr expr) throws CompileError { if (expr.isArray()) atNewArrayExpr(expr); @@ -408,11 +437,13 @@ public class MemberCodeGen extends CodeGen { throw new CompileError("bad new expression"); } + @Override protected void atArrayVariableAssign(ArrayInit init, int varType, int varArray, String varClass) throws CompileError { atNewArrayExpr2(varType, null, varClass, init); } + @Override public void atArrayInit(ArrayInit init) throws CompileError { throw new CompileError("array initializer is not supported"); } @@ -446,6 +477,7 @@ public class MemberCodeGen extends CodeGen { bytecode.addMultiNewarray(desc, count); } + @Override public void atCallExpr(CallExpr expr) throws CompileError { String mname = null; CtClass targetClass = null; @@ -472,8 +504,7 @@ public class MemberCodeGen extends CodeGen { targetClass = thisClass; if (inStaticMethod) throw new CompileError("a constructor cannot be static"); - else - bytecode.addAload(0); // this + bytecode.addAload(0); // this if (((Keyword)method).get() == SUPER) targetClass = MemberResolver.getSuperclass(targetClass); @@ -563,6 +594,7 @@ public class MemberCodeGen extends CodeGen { isStatic = true; } + @SuppressWarnings("unused") int stack = bytecode.getStackDepth(); // generate code for evaluating arguments. @@ -784,6 +816,7 @@ public class MemberCodeGen extends CodeGen { } } + @Override protected void atFieldAssign(Expr expr, int op, ASTree left, ASTree right, boolean doDup) throws CompileError { @@ -842,7 +875,7 @@ public class MemberCodeGen extends CodeGen { bytecode.add(PUTFIELD); bytecode.growStack(is2byte ? -3 : -2); } - + bytecode.addIndex(fi); } else { @@ -858,10 +891,12 @@ public class MemberCodeGen extends CodeGen { /* overwritten in JvstCodeGen. */ + @Override public void atMember(Member mem) throws CompileError { atFieldRead(mem); } + @Override protected void atFieldRead(ASTree expr) throws CompileError { CtField f = fieldAccess(expr, true); @@ -904,20 +939,18 @@ public class MemberCodeGen extends CodeGen { minfo.getDescriptor()); return 0; } + int fi = addFieldrefInfo(f, finfo); + if (isStatic) { + bytecode.add(GETSTATIC); + bytecode.growStack(is2byte ? 2 : 1); + } else { - int fi = addFieldrefInfo(f, finfo); - if (isStatic) { - bytecode.add(GETSTATIC); - bytecode.growStack(is2byte ? 2 : 1); - } - else { - bytecode.add(GETFIELD); - bytecode.growStack(is2byte ? 1 : 0); - } - - bytecode.addIndex(fi); - return fi; + bytecode.add(GETFIELD); + bytecode.growStack(is2byte ? 1 : 0); } + + bytecode.addIndex(fi); + return fi; } /** @@ -929,18 +962,15 @@ public class MemberCodeGen extends CodeGen { throws CompileError { if (AccessFlag.isPrivate(finfo.getAccessFlags()) - && f.getDeclaringClass() != thisClass) { - CtClass declClass = f.getDeclaringClass(); + && f.getDeclaringClass() != thisClass) { + CtClass declClass = f.getDeclaringClass(); if (isEnclosing(declClass, thisClass)) { AccessorMaker maker = declClass.getAccessorMaker(); if (maker != null) return maker; - else - throw new CompileError("fatal error. bug?"); } - else - throw new CompileError("Field " + f.getName() + " in " - + declClass.getName() + " is private."); + throw new CompileError("Field " + f.getName() + " in " + + declClass.getName() + " is private."); } return null; // accessible field @@ -983,6 +1013,7 @@ public class MemberCodeGen extends CodeGen { return cp.addFieldrefInfo(ci, name, type); } + @Override protected void atClassObject2(String cname) throws CompileError { if (getMajorVersion() < ClassFile.JAVA_5) super.atClassObject2(cname); @@ -990,6 +1021,7 @@ public class MemberCodeGen extends CodeGen { bytecode.addLdc(bytecode.getConstPool().addClassInfo(cname)); } + @Override protected void atFieldPlusPlus(int token, boolean isPost, ASTree oprand, Expr expr, boolean doDup) throws CompileError @@ -1130,16 +1162,14 @@ public class MemberCodeGen extends CodeGen { ASTList list = md.getThrows(); if (list == null) return null; - else { - int i = 0; - clist = new CtClass[list.length()]; - while (list != null) { - clist[i++] = resolver.lookupClassByName((ASTList)list.head()); - list = list.tail(); - } - - return clist; + int i = 0; + clist = new CtClass[list.length()]; + while (list != null) { + clist[i++] = resolver.lookupClassByName((ASTList)list.head()); + list = list.tail(); } + + return clist; } /* Converts a class name into a JVM-internal representation. @@ -1147,6 +1177,7 @@ public class MemberCodeGen extends CodeGen { * It may also expand a simple class name to java.lang.*. * For example, this converts Object into java/lang/Object. */ + @Override protected String resolveClassName(ASTList name) throws CompileError { return resolver.resolveClassName(name); } @@ -1154,6 +1185,7 @@ public class MemberCodeGen extends CodeGen { /* Expands a simple class name to java.lang.*. * For example, this converts Object into java/lang/Object. */ + @Override protected String resolveClassName(String jvmName) throws CompileError { return resolver.resolveJvmClassName(jvmName); } diff --git a/src/main/javassist/compiler/MemberResolver.java b/src/main/javassist/compiler/MemberResolver.java index a1073a76..00dac6c1 100644 --- a/src/main/javassist/compiler/MemberResolver.java +++ b/src/main/javassist/compiler/MemberResolver.java @@ -16,15 +16,28 @@ package javassist.compiler; -import java.util.Hashtable; +import java.lang.ref.Reference; import java.lang.ref.WeakReference; -import java.util.WeakHashMap; -import java.util.List; +import java.util.Hashtable; import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; -import javassist.*; -import javassist.bytecode.*; -import javassist.compiler.ast.*; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtField; +import javassist.Modifier; +import javassist.NotFoundException; +import javassist.bytecode.AccessFlag; +import javassist.bytecode.ClassFile; +import javassist.bytecode.Descriptor; +import javassist.bytecode.MethodInfo; +import javassist.compiler.ast.ASTList; +import javassist.compiler.ast.ASTree; +import javassist.compiler.ast.Declarator; +import javassist.compiler.ast.Keyword; +import javassist.compiler.ast.Symbol; /* Code generator methods depending on javassist.* classes. */ @@ -77,8 +90,7 @@ public class MemberResolver implements TokenId { Method r = new Method(clazz, current, res); if (res == YES) return r; - else - maybe = r; + maybe = r; } } @@ -86,8 +98,7 @@ public class MemberResolver implements TokenId { argClassNames, maybe != null); if (m != null) return m; - else - return maybe; + return maybe; } private Method lookupMethod(CtClass clazz, String methodName, @@ -100,10 +111,8 @@ public class MemberResolver implements TokenId { // If the class is an array type, the class file is null. // If so, search the super class java.lang.Object for clone() etc. if (cf != null) { - List list = cf.getMethods(); - int n = list.size(); - for (int i = 0; i < n; ++i) { - MethodInfo minfo = (MethodInfo)list.get(i); + List<MethodInfo> list = cf.getMethods(); + for (MethodInfo minfo:list) { if (minfo.getName().equals(methodName) && (minfo.getAccessFlags() & AccessFlag.BRIDGE) == 0) { int res = compareSignature(minfo.getDescriptor(), @@ -143,9 +152,8 @@ public class MemberResolver implements TokenId { try { CtClass[] ifs = clazz.getInterfaces(); - int size = ifs.length; - for (int i = 0; i < size; ++i) { - Method r = lookupMethod(ifs[i], methodName, + for (CtClass intf:ifs) { + Method r = lookupMethod(intf, methodName, argTypes, argDims, argClassNames, onlyExact); if (r != null) @@ -396,13 +404,13 @@ public class MemberResolver implements TokenId { public CtClass lookupClass(String name, boolean notCheckInner) throws CompileError { - Hashtable cache = getInvalidNames(); - Object found = cache.get(name); + Map<String,String> cache = getInvalidNames(); + String found = cache.get(name); if (found == INVALID) throw new CompileError("no such class: " + name); else if (found != null) try { - return classPool.get((String)found); + return classPool.get(found); } catch (NotFoundException e) {} @@ -419,23 +427,24 @@ public class MemberResolver implements TokenId { } private static final String INVALID = "<invalid>"; - private static WeakHashMap invalidNamesMap = new WeakHashMap(); - private Hashtable invalidNames = null; + private static Map<ClassPool, Reference<Map<String,String>>> invalidNamesMap = + new WeakHashMap<ClassPool, Reference<Map<String,String>>>(); + private Map<String,String> invalidNames = null; // for unit tests public static int getInvalidMapSize() { return invalidNamesMap.size(); } - private Hashtable getInvalidNames() { - Hashtable ht = invalidNames; + private Map<String,String> getInvalidNames() { + Map<String,String> ht = invalidNames; if (ht == null) { synchronized (MemberResolver.class) { - WeakReference ref = (WeakReference)invalidNamesMap.get(classPool); + Reference<Map<String,String>> ref = invalidNamesMap.get(classPool); if (ref != null) - ht = (Hashtable)ref.get(); + ht = ref.get(); if (ht == null) { - ht = new Hashtable(); - invalidNamesMap.put(classPool, new WeakReference(ht)); + ht = new Hashtable<String,String>(); + invalidNamesMap.put(classPool, new WeakReference<Map<String,String>>(ht)); } } @@ -449,10 +458,10 @@ public class MemberResolver implements TokenId { throws CompileError { if (orgName.indexOf('.') < 0) { - Iterator it = classPool.getImportedPackages(); + Iterator<String> it = classPool.getImportedPackages(); while (it.hasNext()) { - String pac = (String)it.next(); - String fqName = pac + '.' + orgName; + String pac = it.next(); + String fqName = pac.replaceAll("\\.$","") + "." + orgName; try { return classPool.get(fqName); } @@ -482,11 +491,9 @@ public class MemberResolver implements TokenId { int i = classname.lastIndexOf('.'); if (notCheckInner || i < 0) throw e; - else { - StringBuffer sbuf = new StringBuffer(classname); - sbuf.setCharAt(i, '$'); - classname = sbuf.toString(); - } + StringBuffer sbuf = new StringBuffer(classname); + sbuf.setCharAt(i, '$'); + classname = sbuf.toString(); } } while (cc == null); return cc; @@ -500,8 +507,7 @@ public class MemberResolver implements TokenId { public String resolveClassName(ASTList name) throws CompileError { if (name == null) return null; - else - return javaToJvmName(lookupClassByName(name).getName()); + return javaToJvmName(lookupClassByName(name).getName()); } /* Expands a simple class name to java.lang.*. @@ -510,8 +516,7 @@ public class MemberResolver implements TokenId { public String resolveJvmClassName(String jvmName) throws CompileError { if (jvmName == null) return null; - else - return javaToJvmName(lookupClassByJvmName(jvmName).getName()); + return javaToJvmName(lookupClassByJvmName(jvmName).getName()); } public static CtClass getSuperclass(CtClass c) throws CompileError { diff --git a/src/main/javassist/compiler/NoFieldException.java b/src/main/javassist/compiler/NoFieldException.java index 7f84ad23..dd878590 100644 --- a/src/main/javassist/compiler/NoFieldException.java +++ b/src/main/javassist/compiler/NoFieldException.java @@ -19,6 +19,8 @@ package javassist.compiler; import javassist.compiler.ast.ASTree; public class NoFieldException extends CompileError { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private String fieldName; private ASTree expr; diff --git a/src/main/javassist/compiler/Parser.java b/src/main/javassist/compiler/Parser.java index 2a1d5d63..c67d49ec 100644 --- a/src/main/javassist/compiler/Parser.java +++ b/src/main/javassist/compiler/Parser.java @@ -16,7 +16,29 @@ package javassist.compiler; -import javassist.compiler.ast.*; +import javassist.compiler.ast.ASTList; +import javassist.compiler.ast.ASTree; +import javassist.compiler.ast.ArrayInit; +import javassist.compiler.ast.AssignExpr; +import javassist.compiler.ast.BinExpr; +import javassist.compiler.ast.CallExpr; +import javassist.compiler.ast.CastExpr; +import javassist.compiler.ast.CondExpr; +import javassist.compiler.ast.Declarator; +import javassist.compiler.ast.DoubleConst; +import javassist.compiler.ast.Expr; +import javassist.compiler.ast.FieldDecl; +import javassist.compiler.ast.InstanceOfExpr; +import javassist.compiler.ast.IntConst; +import javassist.compiler.ast.Keyword; +import javassist.compiler.ast.Member; +import javassist.compiler.ast.MethodDecl; +import javassist.compiler.ast.NewExpr; +import javassist.compiler.ast.Pair; +import javassist.compiler.ast.Stmnt; +import javassist.compiler.ast.StringL; +import javassist.compiler.ast.Symbol; +import javassist.compiler.ast.Variable; public final class Parser implements TokenId { private Lex lex; @@ -34,8 +56,7 @@ public final class Parser implements TokenId { ASTList mem = parseMember1(tbl); if (mem instanceof MethodDecl) return parseMethod2(tbl, (MethodDecl)mem); - else - return mem; + return mem; } /* A method body is not parsed. @@ -63,8 +84,7 @@ public final class Parser implements TokenId { d.setVariable(new Symbol(name)); if (isConstructor || lex.lookAhead() == '(') return parseMethod1(tbl, isConstructor, mods, d); - else - return parseField(tbl, mods, d); + return parseField(tbl, mods, d); } /* field.declaration @@ -188,11 +208,9 @@ public final class Parser implements TokenId { int dim = parseArrayDimension(); return new Declarator(t, dim); } - else { - ASTList name = parseClassType(tbl); - int dim = parseArrayDimension(); - return new Declarator(name, dim); - } + ASTList name = parseClassType(tbl); + int dim = parseArrayDimension(); + return new Declarator(name, dim); } private static boolean isBuiltinType(int t) { @@ -294,8 +312,7 @@ public final class Parser implements TokenId { lex.get(); // '}' if (body == null) return new Stmnt(BLOCK); // empty block - else - return body; + return body; } /* if.statement : IF "(" expression ")" statement @@ -654,8 +671,7 @@ public final class Parser implements TokenId { private ASTree parseInitializer(SymbolTable tbl) throws CompileError { if (lex.lookAhead() == '{') return parseArrayInitializer(tbl); - else - return parseExpression(tbl); + return parseExpression(tbl); } /* array.initializer : @@ -726,8 +742,7 @@ public final class Parser implements TokenId { ASTree elseExpr = parseExpression(tbl); return new CondExpr(cond, thenExpr, elseExpr); } - else - return cond; + return cond; } /* logical.or.expr 10 (operator precedence) @@ -778,8 +793,7 @@ public final class Parser implements TokenId { int p = getOpPrecedence(t); if (p == 0) return expr; - else - expr = binaryExpr2(tbl, expr, p); + expr = binaryExpr2(tbl, expr, p); } } @@ -792,11 +806,9 @@ public final class Parser implements TokenId { int dim = parseArrayDimension(); return new InstanceOfExpr(t, dim, expr); } - else { - ASTList name = parseClassType(tbl); - int dim = parseArrayDimension(); - return new InstanceOfExpr(name, dim, expr); - } + ASTList name = parseClassType(tbl); + int dim = parseArrayDimension(); + return new InstanceOfExpr(name, dim, expr); } private ASTree binaryExpr2(SymbolTable tbl, ASTree expr, int prec) @@ -922,6 +934,7 @@ public final class Parser implements TokenId { } private boolean nextIsBuiltinCast() { + @SuppressWarnings("unused") int t; int i = 2; while ((t = lex.lookAhead(i++)) == '[') @@ -949,6 +962,7 @@ public final class Parser implements TokenId { } private int nextIsClassType(int i) { + @SuppressWarnings("unused") int t; while (lex.lookAhead(++i) == '.') if (lex.lookAhead(++i) != Identifier) @@ -1117,43 +1131,41 @@ public final class Parser implements TokenId { String cname = CodeGen.toJvmTypeName(builtinType, dim); return Expr.make('.', new Symbol(cname), new Member("class")); } - else { - String cname; - switch(builtinType) { - case BOOLEAN : - cname = "java.lang.Boolean"; - break; - case BYTE : - cname = "java.lang.Byte"; - break; - case CHAR : - cname = "java.lang.Character"; - break; - case SHORT : - cname = "java.lang.Short"; - break; - case INT : - cname = "java.lang.Integer"; - break; - case LONG : - cname = "java.lang.Long"; - break; - case FLOAT : - cname = "java.lang.Float"; - break; - case DOUBLE : - cname = "java.lang.Double"; - break; - case VOID : - cname = "java.lang.Void"; - break; - default : - throw new CompileError("invalid builtin type: " - + builtinType); - } - - return Expr.make(MEMBER, new Symbol(cname), new Member("TYPE")); + String cname; + switch(builtinType) { + case BOOLEAN : + cname = "java.lang.Boolean"; + break; + case BYTE : + cname = "java.lang.Byte"; + break; + case CHAR : + cname = "java.lang.Character"; + break; + case SHORT : + cname = "java.lang.Short"; + break; + case INT : + cname = "java.lang.Integer"; + break; + case LONG : + cname = "java.lang.Long"; + break; + case FLOAT : + cname = "java.lang.Float"; + break; + case DOUBLE : + cname = "java.lang.Double"; + break; + case VOID : + cname = "java.lang.Void"; + break; + default : + throw new CompileError("invalid builtin type: " + + builtinType); } + + return Expr.make(MEMBER, new Symbol(cname), new Member("TYPE")); } /* method.call : method.expr "(" argument.list ")" @@ -1236,8 +1248,7 @@ public final class Parser implements TokenId { decl = tbl.lookup(name); if (decl == null) return new Member(name); // this or static member - else - return new Variable(name, decl); // local variable + return new Variable(name, decl); // local variable case StringL : return new StringL(lex.getString()); case NEW : @@ -1246,8 +1257,7 @@ public final class Parser implements TokenId { expr = parseExpression(tbl); if (lex.get() == ')') return expr; - else - throw new CompileError(") is missing", lex); + throw new CompileError(") is missing", lex); default : if (isBuiltinType(t) || t == VOID) { int dim = parseArrayDimension(); @@ -1311,13 +1321,11 @@ public final class Parser implements TokenId { lex.get(); return null; } - else { - ASTree index = parseExpression(tbl); - if (lex.get() != ']') - throw new CompileError("] is missing", lex); + ASTree index = parseExpression(tbl); + if (lex.get() != ']') + throw new CompileError("] is missing", lex); - return index; - } + return index; } /* argument.list : "(" [ expression [ "," expression ]* ] ")" diff --git a/src/main/javassist/compiler/SymbolTable.java b/src/main/javassist/compiler/SymbolTable.java index a8e0dd72..e23f8ac7 100644 --- a/src/main/javassist/compiler/SymbolTable.java +++ b/src/main/javassist/compiler/SymbolTable.java @@ -17,9 +17,12 @@ package javassist.compiler; import java.util.HashMap; + import javassist.compiler.ast.Declarator; -public final class SymbolTable extends HashMap { +public final class SymbolTable extends HashMap<String,Declarator> { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private SymbolTable parent; public SymbolTable() { this(null); } @@ -32,11 +35,10 @@ public final class SymbolTable extends HashMap { public SymbolTable getParent() { return parent; } public Declarator lookup(String name) { - Declarator found = (Declarator)get(name); + Declarator found = get(name); if (found == null && parent != null) return parent.lookup(name); - else - return found; + return found; } public void append(String name, Declarator value) { diff --git a/src/main/javassist/compiler/SyntaxError.java b/src/main/javassist/compiler/SyntaxError.java index fdf357c8..ed759bb0 100644 --- a/src/main/javassist/compiler/SyntaxError.java +++ b/src/main/javassist/compiler/SyntaxError.java @@ -17,6 +17,9 @@ package javassist.compiler; public class SyntaxError extends CompileError { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public SyntaxError(Lex lexer) { super("syntax error near \"" + lexer.getTextAround() + "\"", lexer); } diff --git a/src/main/javassist/compiler/TypeChecker.java b/src/main/javassist/compiler/TypeChecker.java index bd62f806..9e01d0a1 100644 --- a/src/main/javassist/compiler/TypeChecker.java +++ b/src/main/javassist/compiler/TypeChecker.java @@ -16,13 +16,34 @@ package javassist.compiler; +import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; -import javassist.ClassPool; import javassist.Modifier; import javassist.NotFoundException; -import javassist.compiler.ast.*; -import javassist.bytecode.*; +import javassist.bytecode.FieldInfo; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; +import javassist.compiler.ast.ASTList; +import javassist.compiler.ast.ASTree; +import javassist.compiler.ast.ArrayInit; +import javassist.compiler.ast.AssignExpr; +import javassist.compiler.ast.BinExpr; +import javassist.compiler.ast.CallExpr; +import javassist.compiler.ast.CastExpr; +import javassist.compiler.ast.CondExpr; +import javassist.compiler.ast.Declarator; +import javassist.compiler.ast.DoubleConst; +import javassist.compiler.ast.Expr; +import javassist.compiler.ast.InstanceOfExpr; +import javassist.compiler.ast.IntConst; +import javassist.compiler.ast.Keyword; +import javassist.compiler.ast.Member; +import javassist.compiler.ast.NewExpr; +import javassist.compiler.ast.StringL; +import javassist.compiler.ast.Symbol; +import javassist.compiler.ast.Variable; +import javassist.compiler.ast.Visitor; public class TypeChecker extends Visitor implements Opcode, TokenId { static final String javaLangObject = "java.lang.Object"; @@ -139,6 +160,7 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { return resolver.resolveJvmClassName(jvmName); } + @Override public void atNewExpr(NewExpr expr) throws CompileError { if (expr.isArray()) atNewArrayExpr(expr); @@ -177,6 +199,7 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { } } + @Override public void atArrayInit(ArrayInit init) throws CompileError { ASTList list = init; while (list != null) { @@ -190,6 +213,7 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { protected void atMultiNewArray(int type, ASTList classname, ASTList size) throws CompileError { + @SuppressWarnings("unused") int count, dim; dim = size.length(); for (count = 0; size != null; size = size.tail()) { @@ -209,6 +233,7 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { className = null; } + @Override public void atAssignExpr(AssignExpr expr) throws CompileError { // =, %=, &=, *=, /=, +=, -=, ^=, |=, <<=, >>=, >>>= int op = expr.getOperator(); @@ -279,11 +304,13 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { className = cname; } + @Override public void atCondExpr(CondExpr expr) throws CompileError { booleanExpr(expr.condExpr()); expr.thenExpr().accept(this); int type1 = exprType; int dim1 = arrayDim; + @SuppressWarnings("unused") String cname1 = className; expr.elseExpr().accept(this); @@ -302,6 +329,7 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { * (if the original is not '+') and sets the new expression to the * left-hand-side expression and null to the right-hand-side expression. */ + @Override public void atBinExpr(BinExpr expr) throws CompileError { int token = expr.getOperator(); int k = CodeGen.lookupBinOp(token); @@ -384,10 +412,8 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { className = "java/lang/StringBuffer"; return makeAppendCall(makeAppendCall(e, left), right); } - else { - computeBinExprType(expr, '+', type1); - return null; - } + computeBinExprType(expr, '+', type1); + return null; } private boolean isConstant(BinExpr expr, int op, ASTree left, @@ -406,13 +432,11 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { if (newExpr == null) return false; // not a constant expression - else { - expr.setOperator('+'); - expr.setOprand1(newExpr); - expr.setOprand2(null); - newExpr.accept(this); // for setting exprType, arrayDim, ... - return true; - } + expr.setOperator('+'); + expr.setOprand1(newExpr); + expr.setOprand2(null); + newExpr.accept(this); // for setting exprType, arrayDim, ... + return true; } /* CodeGen.atSwitchStmnt() also calls stripPlusExpr(). @@ -542,6 +566,7 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { exprType = type1; } + @Override public void atCastExpr(CastExpr expr) throws CompileError { String cname = resolveClassName(expr.getClassName()); expr.getOprand().accept(this); @@ -550,12 +575,14 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { className = cname; } + @Override public void atInstanceOfExpr(InstanceOfExpr expr) throws CompileError { expr.getOprand().accept(this); exprType = BOOLEAN; arrayDim = 0; } + @Override public void atExpr(Expr expr) throws CompileError { // array access, member access, // (unary) +, (unary) -, ++, --, !, ~ @@ -572,14 +599,14 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { // length might be a class or package name. atFieldRead(expr); } - else if (member.equals("class")) + else if (member.equals("class")) atClassObject(expr); // .class else atFieldRead(expr); } else if (token == MEMBER) { // field read String member = ((Symbol)expr.oprand2()).get(); - if (member.equals("class")) + if (member.equals("class")) atClassObject(expr); // .class else atFieldRead(expr); @@ -629,6 +656,7 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { return true; } + @Override public void atCallExpr(CallExpr expr) throws CompileError { String mname = null; CtClass targetClass = null; @@ -739,7 +767,7 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { mname, types, dims, cnames); if (found == null) { String clazz = targetClass.getName(); - String signature = argTypesToString(types, dims, cnames); + String signature = argTypesToString(types, dims, cnames); String msg; if (mname.equals(MethodInfo.nameInit)) msg = "cannot find constructor " + clazz + signature; @@ -896,7 +924,7 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { * often inconvenient, this compiler allows it. The following * code is for that. */ - ASTree oprnd1 = e.oprand1(); + ASTree oprnd1 = e.oprand1(); if (oprnd1 instanceof Symbol) return fieldAccess2(e, ((Symbol)oprnd1).get()); @@ -984,10 +1012,12 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { exprType = INT; } + @Override public void atMember(Member mem) throws CompileError { atFieldRead(mem); } + @Override public void atVariable(Variable v) throws CompileError { Declarator d = v.getDeclarator(); exprType = d.getType(); @@ -995,6 +1025,7 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { className = d.getClassName(); } + @Override public void atKeyword(Keyword k) throws CompileError { arrayDim = 0; int token = k.get(); @@ -1012,19 +1043,21 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { if (token == THIS) className = getThisName(); else - className = getSuperName(); + className = getSuperName(); break; default : fatal(); } } + @Override public void atStringL(StringL s) throws CompileError { exprType = CLASS; arrayDim = 0; className = jvmJavaLangString; } + @Override public void atIntConst(IntConst i) throws CompileError { arrayDim = 0; int type = i.getType(); @@ -1034,6 +1067,7 @@ public class TypeChecker extends Visitor implements Opcode, TokenId { exprType = LONG; } + @Override public void atDoubleConst(DoubleConst d) throws CompileError { arrayDim = 0; if (d.getType() == DoubleConstant) diff --git a/src/main/javassist/compiler/ast/ASTList.java b/src/main/javassist/compiler/ast/ASTList.java index cf398966..67fbd97a 100644 --- a/src/main/javassist/compiler/ast/ASTList.java +++ b/src/main/javassist/compiler/ast/ASTList.java @@ -23,6 +23,8 @@ import javassist.compiler.CompileError; * The right subtree must be an ASTList object or null. */ public class ASTList extends ASTree { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private ASTree left; private ASTList right; @@ -40,12 +42,16 @@ public class ASTList extends ASTree { return new ASTList(e1, new ASTList(e2, new ASTList(e3))); } + @Override public ASTree getLeft() { return left; } + @Override public ASTree getRight() { return right; } + @Override public void setLeft(ASTree _left) { left = _left; } + @Override public void setRight(ASTree _right) { right = (ASTList)_right; } @@ -68,8 +74,10 @@ public class ASTList extends ASTree { right = _tail; } + @Override public void accept(Visitor v) throws CompileError { v.atASTList(this); } + @Override public String toString() { StringBuffer sbuf = new StringBuffer(); sbuf.append("(<"); @@ -148,13 +156,11 @@ public class ASTList extends ASTree { public static ASTList concat(ASTList a, ASTList b) { if (a == null) return b; - else { - ASTList list = a; - while (list.right != null) - list = list.right; + ASTList list = a; + while (list.right != null) + list = list.right; - list.right = b; - return a; - } + list.right = b; + return a; } } diff --git a/src/main/javassist/compiler/ast/ASTree.java b/src/main/javassist/compiler/ast/ASTree.java index aaad0732..7fd05fd4 100644 --- a/src/main/javassist/compiler/ast/ASTree.java +++ b/src/main/javassist/compiler/ast/ASTree.java @@ -17,6 +17,7 @@ package javassist.compiler.ast; import java.io.Serializable; + import javassist.compiler.CompileError; /** @@ -25,6 +26,9 @@ import javassist.compiler.CompileError; * and <code>getRight()</code> returns null. */ public abstract class ASTree implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public ASTree getLeft() { return null; } public ASTree getRight() { return null; } @@ -40,6 +44,7 @@ public abstract class ASTree implements Serializable { */ public abstract void accept(Visitor v) throws CompileError; + @Override public String toString() { StringBuffer sbuf = new StringBuffer(); sbuf.append('<'); diff --git a/src/main/javassist/compiler/ast/ArrayInit.java b/src/main/javassist/compiler/ast/ArrayInit.java index 26838fca..f992f426 100644 --- a/src/main/javassist/compiler/ast/ArrayInit.java +++ b/src/main/javassist/compiler/ast/ArrayInit.java @@ -22,11 +22,16 @@ import javassist.compiler.CompileError; * Array initializer such as <code>{ 1, 2, 3 }</code>. */ public class ArrayInit extends ASTList { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public ArrayInit(ASTree firstElement) { super(firstElement); } + @Override public void accept(Visitor v) throws CompileError { v.atArrayInit(this); } + @Override public String getTag() { return "array"; } } diff --git a/src/main/javassist/compiler/ast/AssignExpr.java b/src/main/javassist/compiler/ast/AssignExpr.java index 060a5bd3..a5e1857d 100644 --- a/src/main/javassist/compiler/ast/AssignExpr.java +++ b/src/main/javassist/compiler/ast/AssignExpr.java @@ -26,6 +26,9 @@ public class AssignExpr extends Expr { * =, %=, &=, *=, +=, -=, /=, ^=, |=, <<=, >>=, >>>= */ + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + private AssignExpr(int op, ASTree _head, ASTList _tail) { super(op, _head, _tail); } @@ -35,6 +38,7 @@ public class AssignExpr extends Expr { return new AssignExpr(op, oprand1, new ASTList(oprand2)); } + @Override public void accept(Visitor v) throws CompileError { v.atAssignExpr(this); } diff --git a/src/main/javassist/compiler/ast/BinExpr.java b/src/main/javassist/compiler/ast/BinExpr.java index 3b9f8ea2..9630ada9 100644 --- a/src/main/javassist/compiler/ast/BinExpr.java +++ b/src/main/javassist/compiler/ast/BinExpr.java @@ -30,6 +30,9 @@ public class BinExpr extends Expr { * <<, >>, >>>, +, -, *, /, % */ + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + private BinExpr(int op, ASTree _head, ASTList _tail) { super(op, _head, _tail); } @@ -38,5 +41,6 @@ public class BinExpr extends Expr { return new BinExpr(op, oprand1, new ASTList(oprand2)); } + @Override public void accept(Visitor v) throws CompileError { v.atBinExpr(this); } } diff --git a/src/main/javassist/compiler/ast/CallExpr.java b/src/main/javassist/compiler/ast/CallExpr.java index 5e3dd434..395915ed 100644 --- a/src/main/javassist/compiler/ast/CallExpr.java +++ b/src/main/javassist/compiler/ast/CallExpr.java @@ -17,13 +17,15 @@ package javassist.compiler.ast; import javassist.compiler.CompileError; -import javassist.compiler.TokenId; import javassist.compiler.MemberResolver; +import javassist.compiler.TokenId; /** * Method call expression. */ public class CallExpr extends Expr { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private MemberResolver.Method method; // cached result of lookupMethod() private CallExpr(ASTree _head, ASTList _tail) { @@ -43,5 +45,6 @@ public class CallExpr extends Expr { return new CallExpr(target, new ASTList(args)); } + @Override public void accept(Visitor v) throws CompileError { v.atCallExpr(this); } } diff --git a/src/main/javassist/compiler/ast/CastExpr.java b/src/main/javassist/compiler/ast/CastExpr.java index 7d4f4d80..903e5bbd 100644 --- a/src/main/javassist/compiler/ast/CastExpr.java +++ b/src/main/javassist/compiler/ast/CastExpr.java @@ -16,13 +16,15 @@ package javassist.compiler.ast; -import javassist.compiler.TokenId; import javassist.compiler.CompileError; +import javassist.compiler.TokenId; /** * Cast expression. */ public class CastExpr extends ASTList implements TokenId { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected int castType; protected int arrayDim; @@ -50,7 +52,9 @@ public class CastExpr extends ASTList implements TokenId { public void setOprand(ASTree t) { getRight().setLeft(t); } + @Override public String getTag() { return "cast:" + castType + ":" + arrayDim; } + @Override public void accept(Visitor v) throws CompileError { v.atCastExpr(this); } } diff --git a/src/main/javassist/compiler/ast/CondExpr.java b/src/main/javassist/compiler/ast/CondExpr.java index 8645736f..46435012 100644 --- a/src/main/javassist/compiler/ast/CondExpr.java +++ b/src/main/javassist/compiler/ast/CondExpr.java @@ -22,6 +22,9 @@ import javassist.compiler.CompileError; * Conditional expression. */ public class CondExpr extends ASTList { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public CondExpr(ASTree cond, ASTree thenp, ASTree elsep) { super(cond, new ASTList(thenp, new ASTList(elsep))); } @@ -38,7 +41,9 @@ public class CondExpr extends ASTList { public void setElse(ASTree t) { tail().tail().setHead(t); } + @Override public String getTag() { return "?:"; } + @Override public void accept(Visitor v) throws CompileError { v.atCondExpr(this); } } diff --git a/src/main/javassist/compiler/ast/Declarator.java b/src/main/javassist/compiler/ast/Declarator.java index 5f14ac57..24170db0 100644 --- a/src/main/javassist/compiler/ast/Declarator.java +++ b/src/main/javassist/compiler/ast/Declarator.java @@ -16,13 +16,15 @@ package javassist.compiler.ast; -import javassist.compiler.TokenId; import javassist.compiler.CompileError; +import javassist.compiler.TokenId; /** * Variable declarator. */ public class Declarator extends ASTList implements TokenId { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected int varType; protected int arrayDim; protected int localVar; @@ -86,16 +88,17 @@ public class Declarator extends ASTList implements TokenId { ASTList t = tail(); if (t != null) return t.head(); - else - return null; + return null; } public void setLocalVar(int n) { localVar = n; } public int getLocalVar() { return localVar; } + @Override public String getTag() { return "decl"; } + @Override public void accept(Visitor v) throws CompileError { v.atDeclarator(this); } diff --git a/src/main/javassist/compiler/ast/DoubleConst.java b/src/main/javassist/compiler/ast/DoubleConst.java index 23ff0b65..f8d0afde 100644 --- a/src/main/javassist/compiler/ast/DoubleConst.java +++ b/src/main/javassist/compiler/ast/DoubleConst.java @@ -23,6 +23,8 @@ import javassist.compiler.TokenId; * Double constant. */ public class DoubleConst extends ASTree { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected double value; protected int type; @@ -36,8 +38,10 @@ public class DoubleConst extends ASTree { */ public int getType() { return type; } + @Override public String toString() { return Double.toString(value); } + @Override public void accept(Visitor v) throws CompileError { v.atDoubleConst(this); } @@ -63,7 +67,7 @@ public class DoubleConst extends ASTree { } private DoubleConst compute0(int op, IntConst right) { - return compute(op, this.value, (double)right.value, this.type); + return compute(op, this.value, right.value, this.type); } private static DoubleConst compute(int op, double value1, double value2, diff --git a/src/main/javassist/compiler/ast/Expr.java b/src/main/javassist/compiler/ast/Expr.java index bc798bbc..ed5cb60b 100644 --- a/src/main/javassist/compiler/ast/Expr.java +++ b/src/main/javassist/compiler/ast/Expr.java @@ -16,8 +16,8 @@ package javassist.compiler.ast; -import javassist.compiler.TokenId; import javassist.compiler.CompileError; +import javassist.compiler.TokenId; /** * Expression. @@ -29,6 +29,8 @@ public class Expr extends ASTList implements TokenId { * Otherwise, the object should be an instance of a subclass. */ + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected int operatorId; Expr(int op, ASTree _head, ASTList _tail) { @@ -65,6 +67,7 @@ public class Expr extends ASTList implements TokenId { getRight().setLeft(expr); } + @Override public void accept(Visitor v) throws CompileError { v.atExpr(this); } public String getName() { @@ -79,6 +82,7 @@ public class Expr extends ASTList implements TokenId { return String.valueOf(id); } + @Override protected String getTag() { return "op:" + getName(); } diff --git a/src/main/javassist/compiler/ast/FieldDecl.java b/src/main/javassist/compiler/ast/FieldDecl.java index 82d4856c..e2a066e9 100644 --- a/src/main/javassist/compiler/ast/FieldDecl.java +++ b/src/main/javassist/compiler/ast/FieldDecl.java @@ -19,6 +19,9 @@ package javassist.compiler.ast; import javassist.compiler.CompileError; public class FieldDecl extends ASTList { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public FieldDecl(ASTree _head, ASTList _tail) { super(_head, _tail); } @@ -27,8 +30,9 @@ public class FieldDecl extends ASTList { public Declarator getDeclarator() { return (Declarator)tail().head(); } - public ASTree getInit() { return (ASTree)sublist(2).head(); } + public ASTree getInit() { return sublist(2).head(); } + @Override public void accept(Visitor v) throws CompileError { v.atFieldDecl(this); } diff --git a/src/main/javassist/compiler/ast/InstanceOfExpr.java b/src/main/javassist/compiler/ast/InstanceOfExpr.java index cddf0317..ddf07bd2 100644 --- a/src/main/javassist/compiler/ast/InstanceOfExpr.java +++ b/src/main/javassist/compiler/ast/InstanceOfExpr.java @@ -22,6 +22,9 @@ import javassist.compiler.CompileError; * Instanceof expression. */ public class InstanceOfExpr extends CastExpr { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public InstanceOfExpr(ASTList className, int dim, ASTree expr) { super(className, dim, expr); } @@ -30,10 +33,12 @@ public class InstanceOfExpr extends CastExpr { super(type, dim, expr); } + @Override public String getTag() { return "instanceof:" + castType + ":" + arrayDim; } + @Override public void accept(Visitor v) throws CompileError { v.atInstanceOfExpr(this); } diff --git a/src/main/javassist/compiler/ast/IntConst.java b/src/main/javassist/compiler/ast/IntConst.java index 90feeb58..7040b0c9 100644 --- a/src/main/javassist/compiler/ast/IntConst.java +++ b/src/main/javassist/compiler/ast/IntConst.java @@ -23,6 +23,8 @@ import javassist.compiler.TokenId; * Integer constant. */ public class IntConst extends ASTree { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected long value; protected int type; @@ -36,8 +38,10 @@ public class IntConst extends ASTree { */ public int getType() { return type; } + @Override public String toString() { return Long.toString(value); } + @Override public void accept(Visitor v) throws CompileError { v.atIntConst(this); } @@ -111,7 +115,7 @@ public class IntConst extends ASTree { } private DoubleConst compute0(int op, DoubleConst right) { - double value1 = (double)this.value; + double value1 = this.value; double value2 = right.value; double newValue; switch (op) { diff --git a/src/main/javassist/compiler/ast/Keyword.java b/src/main/javassist/compiler/ast/Keyword.java index 8127dc1e..b509375c 100644 --- a/src/main/javassist/compiler/ast/Keyword.java +++ b/src/main/javassist/compiler/ast/Keyword.java @@ -22,6 +22,8 @@ import javassist.compiler.CompileError; * Keyword. */ public class Keyword extends ASTree { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected int tokenId; public Keyword(int token) { @@ -30,7 +32,9 @@ public class Keyword extends ASTree { public int get() { return tokenId; } + @Override public String toString() { return "id:" + tokenId; } + @Override public void accept(Visitor v) throws CompileError { v.atKeyword(this); } } diff --git a/src/main/javassist/compiler/ast/Member.java b/src/main/javassist/compiler/ast/Member.java index f77de616..192c9ef3 100644 --- a/src/main/javassist/compiler/ast/Member.java +++ b/src/main/javassist/compiler/ast/Member.java @@ -16,13 +16,15 @@ package javassist.compiler.ast; -import javassist.compiler.CompileError; import javassist.CtField; +import javassist.compiler.CompileError; /** * Member name. */ public class Member extends Symbol { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; // cache maintained by fieldAccess() in TypeChecker. // this is used to obtain the value of a static final field. private CtField field; @@ -36,5 +38,6 @@ public class Member extends Symbol { public CtField getField() { return field; } + @Override public void accept(Visitor v) throws CompileError { v.atMember(this); } } diff --git a/src/main/javassist/compiler/ast/MethodDecl.java b/src/main/javassist/compiler/ast/MethodDecl.java index 0a7d828f..d96e3d4d 100644 --- a/src/main/javassist/compiler/ast/MethodDecl.java +++ b/src/main/javassist/compiler/ast/MethodDecl.java @@ -19,6 +19,8 @@ package javassist.compiler.ast; import javassist.compiler.CompileError; public class MethodDecl extends ASTList { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; public static final String initName = "<init>"; public MethodDecl(ASTree _head, ASTList _tail) { @@ -40,6 +42,7 @@ public class MethodDecl extends ASTList { public Stmnt getBody() { return (Stmnt)sublist(4).head(); } + @Override public void accept(Visitor v) throws CompileError { v.atMethodDecl(this); } diff --git a/src/main/javassist/compiler/ast/NewExpr.java b/src/main/javassist/compiler/ast/NewExpr.java index b1413f60..44b264c0 100644 --- a/src/main/javassist/compiler/ast/NewExpr.java +++ b/src/main/javassist/compiler/ast/NewExpr.java @@ -16,13 +16,15 @@ package javassist.compiler.ast; -import javassist.compiler.TokenId; import javassist.compiler.CompileError; +import javassist.compiler.TokenId; /** * New Expression. */ public class NewExpr extends ASTList implements TokenId { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected boolean newArray; protected int arrayType; @@ -66,12 +68,13 @@ public class NewExpr extends ASTList implements TokenId { ASTree t = getRight().getRight(); if (t == null) return null; - else - return (ArrayInit)t.getLeft(); + return (ArrayInit)t.getLeft(); } + @Override public void accept(Visitor v) throws CompileError { v.atNewExpr(this); } + @Override protected String getTag() { return newArray ? "new[]" : "new"; } diff --git a/src/main/javassist/compiler/ast/Pair.java b/src/main/javassist/compiler/ast/Pair.java index b050dd28..840c1145 100644 --- a/src/main/javassist/compiler/ast/Pair.java +++ b/src/main/javassist/compiler/ast/Pair.java @@ -23,6 +23,8 @@ import javassist.compiler.CompileError; * overriding abstract methods in ASTree. */ public class Pair extends ASTree { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected ASTree left, right; public Pair(ASTree _left, ASTree _right) { @@ -30,8 +32,10 @@ public class Pair extends ASTree { right = _right; } + @Override public void accept(Visitor v) throws CompileError { v.atPair(this); } + @Override public String toString() { StringBuffer sbuf = new StringBuffer(); sbuf.append("(<Pair> "); @@ -42,11 +46,15 @@ public class Pair extends ASTree { return sbuf.toString(); } + @Override public ASTree getLeft() { return left; } + @Override public ASTree getRight() { return right; } + @Override public void setLeft(ASTree _left) { left = _left; } + @Override public void setRight(ASTree _right) { right = _right; } } diff --git a/src/main/javassist/compiler/ast/Stmnt.java b/src/main/javassist/compiler/ast/Stmnt.java index 251f66c3..c5aa5df3 100644 --- a/src/main/javassist/compiler/ast/Stmnt.java +++ b/src/main/javassist/compiler/ast/Stmnt.java @@ -16,13 +16,15 @@ package javassist.compiler.ast; -import javassist.compiler.TokenId; import javassist.compiler.CompileError; +import javassist.compiler.TokenId; /** * Statement. */ public class Stmnt extends ASTList implements TokenId { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected int operatorId; public Stmnt(int op, ASTree _head, ASTList _tail) { @@ -47,14 +49,15 @@ public class Stmnt extends ASTList implements TokenId { return new Stmnt(op, op1, new ASTList(op2, new ASTList(op3))); } + @Override public void accept(Visitor v) throws CompileError { v.atStmnt(this); } public int getOperator() { return operatorId; } + @Override protected String getTag() { if (operatorId < 128) return "stmnt:" + (char)operatorId; - else - return "stmnt:" + operatorId; + return "stmnt:" + operatorId; } } diff --git a/src/main/javassist/compiler/ast/StringL.java b/src/main/javassist/compiler/ast/StringL.java index f52186e5..7c7e00c3 100644 --- a/src/main/javassist/compiler/ast/StringL.java +++ b/src/main/javassist/compiler/ast/StringL.java @@ -22,6 +22,8 @@ import javassist.compiler.CompileError; * String literal. */ public class StringL extends ASTree { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected String text; public StringL(String t) { @@ -30,7 +32,9 @@ public class StringL extends ASTree { public String get() { return text; } + @Override public String toString() { return "\"" + text + "\""; } + @Override public void accept(Visitor v) throws CompileError { v.atStringL(this); } } diff --git a/src/main/javassist/compiler/ast/Symbol.java b/src/main/javassist/compiler/ast/Symbol.java index f71d0f91..2b66207a 100644 --- a/src/main/javassist/compiler/ast/Symbol.java +++ b/src/main/javassist/compiler/ast/Symbol.java @@ -22,6 +22,8 @@ import javassist.compiler.CompileError; * Identifier. */ public class Symbol extends ASTree { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected String identifier; public Symbol(String sym) { @@ -30,7 +32,9 @@ public class Symbol extends ASTree { public String get() { return identifier; } + @Override public String toString() { return identifier; } + @Override public void accept(Visitor v) throws CompileError { v.atSymbol(this); } } diff --git a/src/main/javassist/compiler/ast/Variable.java b/src/main/javassist/compiler/ast/Variable.java index 88a31daa..c9224a7a 100644 --- a/src/main/javassist/compiler/ast/Variable.java +++ b/src/main/javassist/compiler/ast/Variable.java @@ -22,6 +22,8 @@ import javassist.compiler.CompileError; * Variable. */ public class Variable extends Symbol { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected Declarator declarator; public Variable(String sym, Declarator d) { @@ -31,9 +33,11 @@ public class Variable extends Symbol { public Declarator getDeclarator() { return declarator; } + @Override public String toString() { return identifier + ":" + declarator.getType(); } + @Override public void accept(Visitor v) throws CompileError { v.atVariable(this); } } diff --git a/src/main/javassist/convert/TransformAccessArrayField.java b/src/main/javassist/convert/TransformAccessArrayField.java index 2767d7be..6dab42a5 100644 --- a/src/main/javassist/convert/TransformAccessArrayField.java +++ b/src/main/javassist/convert/TransformAccessArrayField.java @@ -16,10 +16,9 @@ package javassist.convert; import javassist.CannotCompileException; -import javassist.ClassPool; +import javassist.CodeConverter.ArrayAccessReplacementMethodNames; import javassist.CtClass; import javassist.NotFoundException; -import javassist.CodeConverter.ArrayAccessReplacementMethodNames; import javassist.bytecode.BadBytecode; import javassist.bytecode.CodeIterator; import javassist.bytecode.ConstPool; @@ -49,6 +48,7 @@ public final class TransformAccessArrayField extends Transformer { } + @Override public void initialize(ConstPool cp, CtClass clazz, MethodInfo minfo) throws CannotCompileException { /* * This transformer must be isolated from other transformers, since some @@ -85,11 +85,13 @@ public final class TransformAccessArrayField extends Transformer { } } + @Override public void clean() { frames = null; offset = -1; } + @Override public int transform(CtClass tclazz, int pos, CodeIterator iterator, ConstPool cp) throws BadBytecode { // Do nothing, see above comment diff --git a/src/main/javassist/convert/TransformAfter.java b/src/main/javassist/convert/TransformAfter.java index 141fe7bd..30086099 100644 --- a/src/main/javassist/convert/TransformAfter.java +++ b/src/main/javassist/convert/TransformAfter.java @@ -18,7 +18,8 @@ package javassist.convert; import javassist.CtMethod; import javassist.NotFoundException; -import javassist.bytecode.*; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.CodeIterator; public class TransformAfter extends TransformBefore { public TransformAfter(Transformer next, @@ -28,6 +29,7 @@ public class TransformAfter extends TransformBefore { super(next, origMethod, afterMethod); } + @Override protected int match2(int pos, CodeIterator iterator) throws BadBytecode { iterator.move(pos); iterator.insert(saveCode); diff --git a/src/main/javassist/convert/TransformBefore.java b/src/main/javassist/convert/TransformBefore.java index aa2618ed..6471b205 100644 --- a/src/main/javassist/convert/TransformBefore.java +++ b/src/main/javassist/convert/TransformBefore.java @@ -19,7 +19,12 @@ package javassist.convert; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; -import javassist.bytecode.*; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; public class TransformBefore extends TransformCall { protected CtClass[] parameterTypes; @@ -42,6 +47,7 @@ public class TransformBefore extends TransformCall { saveCode = loadCode = null; } + @Override public void initialize(ConstPool cp, CodeAttribute attr) { super.initialize(cp, attr); locals = 0; @@ -49,6 +55,7 @@ public class TransformBefore extends TransformCall { saveCode = loadCode = null; } + @Override protected int match(int c, int pos, CodeIterator iterator, int typedesc, ConstPool cp) throws BadBytecode { @@ -78,6 +85,7 @@ public class TransformBefore extends TransformCall { return iterator.next(); } + @Override public int extraLocals() { return locals; } protected void makeCode(CtClass[] paramTypes, ConstPool cp) { diff --git a/src/main/javassist/convert/TransformCall.java b/src/main/javassist/convert/TransformCall.java index 09249280..fefbe8ae 100644 --- a/src/main/javassist/convert/TransformCall.java +++ b/src/main/javassist/convert/TransformCall.java @@ -16,12 +16,15 @@ package javassist.convert; +import javassist.ClassPool; import javassist.CtClass; import javassist.CtMethod; -import javassist.ClassPool; import javassist.Modifier; import javassist.NotFoundException; -import javassist.bytecode.*; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; public class TransformCall extends Transformer { protected String classname, methodname, methodDescriptor; @@ -51,6 +54,7 @@ public class TransformCall extends Transformer { newMethodIsPrivate = Modifier.isPrivate(substMethod.getModifiers()); } + @Override public void initialize(ConstPool cp, CodeAttribute attr) { if (constPool != cp) newIndex = 0; @@ -63,6 +67,7 @@ public class TransformCall extends Transformer { * by <code>classname</code>. This method transforms the instruction * in that case unless the subclass overrides the target method. */ + @Override public int transform(CtClass clazz, int pos, CodeIterator iterator, ConstPool cp) throws BadBytecode { diff --git a/src/main/javassist/convert/TransformFieldAccess.java b/src/main/javassist/convert/TransformFieldAccess.java index 093fb817..681acc52 100644 --- a/src/main/javassist/convert/TransformFieldAccess.java +++ b/src/main/javassist/convert/TransformFieldAccess.java @@ -16,10 +16,12 @@ package javassist.convert; -import javassist.bytecode.*; import javassist.CtClass; import javassist.CtField; import javassist.Modifier; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; final public class TransformFieldAccess extends Transformer { private String newClassname, newFieldname; @@ -43,6 +45,7 @@ final public class TransformFieldAccess extends Transformer { this.constPool = null; } + @Override public void initialize(ConstPool cp, CodeAttribute attr) { if (constPool != cp) newIndex = 0; @@ -54,6 +57,7 @@ final public class TransformFieldAccess extends Transformer { * in a superclass of the class in which the original field is * declared. */ + @Override public int transform(CtClass clazz, int pos, CodeIterator iterator, ConstPool cp) { diff --git a/src/main/javassist/convert/TransformNew.java b/src/main/javassist/convert/TransformNew.java index 2dd0b7b7..23c9c7a9 100644 --- a/src/main/javassist/convert/TransformNew.java +++ b/src/main/javassist/convert/TransformNew.java @@ -16,9 +16,14 @@ package javassist.convert; -import javassist.bytecode.*; -import javassist.CtClass; import javassist.CannotCompileException; +import javassist.CtClass; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.StackMap; +import javassist.bytecode.StackMapTable; final public class TransformNew extends Transformer { private int nested; @@ -32,6 +37,7 @@ final public class TransformNew extends Transformer { this.trapMethod = trapMethod; } + @Override public void initialize(ConstPool cp, CodeAttribute attr) { nested = 0; } @@ -48,6 +54,7 @@ final public class TransformNew extends Transformer { * ... * INVOKESTATIC trapMethod in trapClass */ + @Override public int transform(CtClass clazz, int pos, CodeIterator iterator, ConstPool cp) throws CannotCompileException { diff --git a/src/main/javassist/convert/TransformNewClass.java b/src/main/javassist/convert/TransformNewClass.java index a13f7c81..83f2a0cc 100644 --- a/src/main/javassist/convert/TransformNewClass.java +++ b/src/main/javassist/convert/TransformNewClass.java @@ -16,9 +16,11 @@ package javassist.convert; -import javassist.bytecode.*; -import javassist.CtClass; import javassist.CannotCompileException; +import javassist.CtClass; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; final public class TransformNewClass extends Transformer { private int nested; @@ -32,6 +34,7 @@ final public class TransformNewClass extends Transformer { this.newClassName = newClassName; } + @Override public void initialize(ConstPool cp, CodeAttribute attr) { nested = 0; newClassIndex = newMethodNTIndex = newMethodIndex = 0; @@ -44,6 +47,7 @@ final public class TransformNewClass extends Transformer { * ... * INVOKESPECIAL classname:method */ + @Override public int transform(CtClass clazz, int pos, CodeIterator iterator, ConstPool cp) throws CannotCompileException { diff --git a/src/main/javassist/convert/TransformReadField.java b/src/main/javassist/convert/TransformReadField.java index 93e48201..e5e373c9 100644 --- a/src/main/javassist/convert/TransformReadField.java +++ b/src/main/javassist/convert/TransformReadField.java @@ -16,12 +16,14 @@ package javassist.convert; -import javassist.bytecode.*; import javassist.ClassPool; import javassist.CtClass; import javassist.CtField; -import javassist.NotFoundException; import javassist.Modifier; +import javassist.NotFoundException; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; public class TransformReadField extends Transformer { protected String fieldname; @@ -66,6 +68,7 @@ public class TransformReadField extends Transformer { return false; } + @Override public int transform(CtClass tclazz, int pos, CodeIterator iterator, ConstPool cp) throws BadBytecode { diff --git a/src/main/javassist/convert/TransformWriteField.java b/src/main/javassist/convert/TransformWriteField.java index 6d6757e2..dd3ddb12 100644 --- a/src/main/javassist/convert/TransformWriteField.java +++ b/src/main/javassist/convert/TransformWriteField.java @@ -18,7 +18,10 @@ package javassist.convert; import javassist.CtClass; import javassist.CtField; -import javassist.bytecode.*; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; final public class TransformWriteField extends TransformReadField { public TransformWriteField(Transformer next, CtField field, @@ -27,6 +30,7 @@ final public class TransformWriteField extends TransformReadField { super(next, field, methodClassname, methodName); } + @Override public int transform(CtClass tclazz, int pos, CodeIterator iterator, ConstPool cp) throws BadBytecode { diff --git a/src/main/javassist/expr/Cast.java b/src/main/javassist/expr/Cast.java index 0ba94d80..31522e5a 100644 --- a/src/main/javassist/expr/Cast.java +++ b/src/main/javassist/expr/Cast.java @@ -16,9 +16,23 @@ package javassist.expr; -import javassist.*; -import javassist.bytecode.*; -import javassist.compiler.*; +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtBehavior; +import javassist.CtClass; +import javassist.NotFoundException; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; +import javassist.compiler.CompileError; +import javassist.compiler.Javac; +import javassist.compiler.JvstCodeGen; +import javassist.compiler.JvstTypeChecker; +import javassist.compiler.ProceedHandler; import javassist.compiler.ast.ASTList; /** @@ -36,6 +50,7 @@ public class Cast extends Expr { * Returns the method or constructor containing the type cast * expression represented by this object. */ + @Override public CtBehavior where() { return super.where(); } /** @@ -44,6 +59,7 @@ public class Cast extends Expr { * * @return -1 if this information is not available. */ + @Override public int getLineNumber() { return super.getLineNumber(); } @@ -53,6 +69,7 @@ public class Cast extends Expr { * * @return null if this information is not available. */ + @Override public String getFileName() { return super.getFileName(); } @@ -75,6 +92,7 @@ public class Cast extends Expr { * including the expression can catch and the exceptions that * the throws declaration allows the method to throw. */ + @Override public CtClass[] mayThrow() { return super.mayThrow(); } @@ -87,8 +105,10 @@ public class Cast extends Expr { * * @param statement a Java statement except try-catch. */ + @Override public void replace(String statement) throws CannotCompileException { thisClass.getClassFile(); // to call checkModify(). + @SuppressWarnings("unused") ConstPool constPool = getConstPool(); int pos = currentPos; int index = iterator.u16bitAt(pos + 1); @@ -142,6 +162,7 @@ public class Cast extends Expr { retType = t; } + @Override public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args) throws CompileError { @@ -155,7 +176,8 @@ public class Cast extends Expr { bytecode.addIndex(index); gen.setType(retType); } - + + @Override public void setReturnType(JvstTypeChecker c, ASTList args) throws CompileError { diff --git a/src/main/javassist/expr/ConstructorCall.java b/src/main/javassist/expr/ConstructorCall.java index 83c38f3e..343e2a09 100644 --- a/src/main/javassist/expr/ConstructorCall.java +++ b/src/main/javassist/expr/ConstructorCall.java @@ -40,6 +40,7 @@ public class ConstructorCall extends MethodCall { /** * Returns <code>"super"</code> or "<code>"this"</code>. */ + @Override public String getMethodName() { return isSuper() ? "super" : "this"; } @@ -49,6 +50,7 @@ public class ConstructorCall extends MethodCall { * * @see #getConstructor() */ + @Override public CtMethod getMethod() throws NotFoundException { throw new NotFoundException("this is a constructor call. Call getConstructor()."); } @@ -64,6 +66,7 @@ public class ConstructorCall extends MethodCall { * Returns true if the called constructor is not <code>this()</code> * but <code>super()</code> (a constructor declared in the super class). */ + @Override public boolean isSuper() { return super.isSuper(); } diff --git a/src/main/javassist/expr/Expr.java b/src/main/javassist/expr/Expr.java index 54aa4bf3..aea43d55 100644 --- a/src/main/javassist/expr/Expr.java +++ b/src/main/javassist/expr/Expr.java @@ -16,6 +16,9 @@ package javassist.expr; +import java.util.LinkedList; +import java.util.List; + import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtBehavior; @@ -36,9 +39,6 @@ import javassist.bytecode.MethodInfo; import javassist.bytecode.Opcode; import javassist.compiler.Javac; -import java.util.Iterator; -import java.util.LinkedList; - /** * Expression. */ @@ -132,7 +132,7 @@ public abstract class Expr implements Opcode { public CtClass[] mayThrow() { ClassPool pool = thisClass.getClassPool(); ConstPool cp = thisMethod.getConstPool(); - LinkedList list = new LinkedList(); + List<CtClass> list = new LinkedList<CtClass>(); try { CodeAttribute ca = thisMethod.getCodeAttribute(); ExceptionTable et = ca.getExceptionTable(); @@ -166,14 +166,12 @@ public abstract class Expr implements Opcode { } } - return (CtClass[])list.toArray(new CtClass[list.size()]); + return list.toArray(new CtClass[list.size()]); } - private static void addClass(LinkedList list, CtClass c) { - Iterator it = list.iterator(); - while (it.hasNext()) - if (it.next() == c) - return; + private static void addClass(List<CtClass> list, CtClass c) { + if (list.contains(c)) + return; list.add(c); } @@ -189,7 +187,7 @@ public abstract class Expr implements Opcode { /** * Returns the line number of the source line containing the expression. - * + * * @return -1 if this information is not available. */ public int getLineNumber() { @@ -205,8 +203,7 @@ public abstract class Expr implements Opcode { ClassFile cf = thisClass.getClassFile2(); if (cf == null) return null; - else - return cf.getSourceFile(); + return cf.getSourceFile(); } static final boolean checkResultValue(CtClass retType, String prog) @@ -243,17 +240,15 @@ public abstract class Expr implements Opcode { Bytecode bytecode) { if (i >= n) return; - else { - CtClass c = params[i]; - int size; - if (c instanceof CtPrimitiveType) - size = ((CtPrimitiveType)c).getDataSize(); - else - size = 1; - - storeStack0(i + 1, n, params, regno + size, bytecode); - bytecode.addStore(regno, c); - } + CtClass c = params[i]; + int size; + if (c instanceof CtPrimitiveType) + size = ((CtPrimitiveType)c).getDataSize(); + else + size = 1; + + storeStack0(i + 1, n, params, regno + size, bytecode); + bytecode.addStore(regno, c); } // The implementation of replace() should call thisClass.checkModify() diff --git a/src/main/javassist/expr/ExprEditor.java b/src/main/javassist/expr/ExprEditor.java index 107b62a1..0b3f934e 100644 --- a/src/main/javassist/expr/ExprEditor.java +++ b/src/main/javassist/expr/ExprEditor.java @@ -16,9 +16,14 @@ package javassist.expr; -import javassist.bytecode.*; -import javassist.CtClass; import javassist.CannotCompileException; +import javassist.CtClass; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ExceptionTable; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; /** * A translator of method bodies. @@ -246,8 +251,7 @@ public class ExprEditor { context.updateMax(expr.locals(), expr.stack()); return true; } - else - return false; + return false; } catch (BadBytecode e) { throw new CannotCompileException(e); diff --git a/src/main/javassist/expr/FieldAccess.java b/src/main/javassist/expr/FieldAccess.java index 18fb8346..335314a5 100644 --- a/src/main/javassist/expr/FieldAccess.java +++ b/src/main/javassist/expr/FieldAccess.java @@ -16,9 +16,26 @@ package javassist.expr; -import javassist.*; -import javassist.bytecode.*; -import javassist.compiler.*; +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtBehavior; +import javassist.CtClass; +import javassist.CtField; +import javassist.CtPrimitiveType; +import javassist.NotFoundException; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; +import javassist.compiler.CompileError; +import javassist.compiler.Javac; +import javassist.compiler.JvstCodeGen; +import javassist.compiler.JvstTypeChecker; +import javassist.compiler.ProceedHandler; import javassist.compiler.ast.ASTList; /** @@ -37,6 +54,7 @@ public class FieldAccess extends Expr { * Returns the method or constructor containing the field-access * expression represented by this object. */ + @Override public CtBehavior where() { return super.where(); } /** @@ -45,6 +63,7 @@ public class FieldAccess extends Expr { * * @return -1 if this information is not available. */ + @Override public int getLineNumber() { return super.getLineNumber(); } @@ -54,6 +73,7 @@ public class FieldAccess extends Expr { * * @return null if this information is not available. */ + @Override public String getFileName() { return super.getFileName(); } @@ -122,6 +142,7 @@ public class FieldAccess extends Expr { * including the expression can catch and the exceptions that * the throws declaration allows the method to throw. */ + @Override public CtClass[] mayThrow() { return super.mayThrow(); } @@ -149,6 +170,7 @@ public class FieldAccess extends Expr { * * @param statement a Java statement except try-catch. */ + @Override public void replace(String statement) throws CannotCompileException { thisClass.getClassFile(); // to call checkModify(). ConstPool constPool = getConstPool(); @@ -236,6 +258,7 @@ public class FieldAccess extends Expr { index = i; } + @Override public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args) throws CompileError { @@ -262,6 +285,7 @@ public class FieldAccess extends Expr { gen.setType(fieldType); } + @Override public void setReturnType(JvstTypeChecker c, ASTList args) throws CompileError { @@ -284,6 +308,7 @@ public class FieldAccess extends Expr { index = i; } + @Override public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args) throws CompileError { @@ -314,6 +339,7 @@ public class FieldAccess extends Expr { gen.addNullIfVoid(); } + @Override public void setReturnType(JvstTypeChecker c, ASTList args) throws CompileError { diff --git a/src/main/javassist/expr/Handler.java b/src/main/javassist/expr/Handler.java index 40fb2c7f..1839abca 100644 --- a/src/main/javassist/expr/Handler.java +++ b/src/main/javassist/expr/Handler.java @@ -16,9 +16,19 @@ package javassist.expr; -import javassist.*; -import javassist.bytecode.*; -import javassist.compiler.*; +import javassist.CannotCompileException; +import javassist.CtBehavior; +import javassist.CtClass; +import javassist.NotFoundException; +import javassist.bytecode.Bytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.ExceptionTable; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; +import javassist.compiler.CompileError; +import javassist.compiler.Javac; /** * A <code>catch</code> clause or a <code>finally</code> block. @@ -41,6 +51,7 @@ public class Handler extends Expr { /** * Returns the method or constructor containing the catch clause. */ + @Override public CtBehavior where() { return super.where(); } /** @@ -48,6 +59,7 @@ public class Handler extends Expr { * * @return -1 if this information is not available. */ + @Override public int getLineNumber() { return super.getLineNumber(); } @@ -57,6 +69,7 @@ public class Handler extends Expr { * * @return null if this information is not available. */ + @Override public String getFileName() { return super.getFileName(); } @@ -64,6 +77,7 @@ public class Handler extends Expr { /** * Returns the list of exceptions that the catch clause may throw. */ + @Override public CtClass[] mayThrow() { return super.mayThrow(); } @@ -76,11 +90,9 @@ public class Handler extends Expr { int type = etable.catchType(index); if (type == 0) return null; - else { - ConstPool cp = getConstPool(); - String name = cp.getClassInfo(type); - return thisClass.getClassPool().getCtClass(name); - } + ConstPool cp = getConstPool(); + String name = cp.getClassInfo(type); + return thisClass.getClassPool().getCtClass(name); } /** @@ -95,6 +107,7 @@ public class Handler extends Expr { * * @param statement a Java statement except try-catch. */ + @Override public void replace(String statement) throws CannotCompileException { throw new RuntimeException("not implemented yet"); } @@ -109,6 +122,7 @@ public class Handler extends Expr { public void insertBefore(String src) throws CannotCompileException { edited = true; + @SuppressWarnings("unused") ConstPool cp = getConstPool(); CodeAttribute ca = iterator.get(); Javac jv = new Javac(thisClass); diff --git a/src/main/javassist/expr/Instanceof.java b/src/main/javassist/expr/Instanceof.java index 6d9cdc94..a046ddbc 100644 --- a/src/main/javassist/expr/Instanceof.java +++ b/src/main/javassist/expr/Instanceof.java @@ -16,9 +16,23 @@ package javassist.expr; -import javassist.*; -import javassist.bytecode.*; -import javassist.compiler.*; +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtBehavior; +import javassist.CtClass; +import javassist.NotFoundException; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; +import javassist.compiler.CompileError; +import javassist.compiler.Javac; +import javassist.compiler.JvstCodeGen; +import javassist.compiler.JvstTypeChecker; +import javassist.compiler.ProceedHandler; import javassist.compiler.ast.ASTList; /** @@ -37,6 +51,7 @@ public class Instanceof extends Expr { * Returns the method or constructor containing the instanceof * expression represented by this object. */ + @Override public CtBehavior where() { return super.where(); } /** @@ -45,6 +60,7 @@ public class Instanceof extends Expr { * * @return -1 if this information is not available. */ + @Override public int getLineNumber() { return super.getLineNumber(); } @@ -55,6 +71,7 @@ public class Instanceof extends Expr { * * @return null if this information is not available. */ + @Override public String getFileName() { return super.getFileName(); } @@ -78,6 +95,7 @@ public class Instanceof extends Expr { * including the expression can catch and the exceptions that * the throws declaration allows the method to throw. */ + @Override public CtClass[] mayThrow() { return super.mayThrow(); } @@ -90,8 +108,10 @@ public class Instanceof extends Expr { * * @param statement a Java statement except try-catch. */ + @Override public void replace(String statement) throws CannotCompileException { thisClass.getClassFile(); // to call checkModify(). + @SuppressWarnings("unused") ConstPool constPool = getConstPool(); int pos = currentPos; int index = iterator.u16bitAt(pos + 1); @@ -146,6 +166,7 @@ public class Instanceof extends Expr { index = i; } + @Override public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args) throws CompileError { @@ -160,6 +181,7 @@ public class Instanceof extends Expr { gen.setType(CtClass.booleanType); } + @Override public void setReturnType(JvstTypeChecker c, ASTList args) throws CompileError { diff --git a/src/main/javassist/expr/MethodCall.java b/src/main/javassist/expr/MethodCall.java index 0fbdf0c3..66ddeadd 100644 --- a/src/main/javassist/expr/MethodCall.java +++ b/src/main/javassist/expr/MethodCall.java @@ -16,9 +16,21 @@ package javassist.expr; -import javassist.*; -import javassist.bytecode.*; -import javassist.compiler.*; +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtBehavior; +import javassist.CtClass; +import javassist.CtMethod; +import javassist.NotFoundException; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.MethodInfo; +import javassist.compiler.CompileError; +import javassist.compiler.Javac; /** * Method invocation (caller-side expression). @@ -39,14 +51,14 @@ public class MethodCall extends Expr { if (c == INVOKEINTERFACE) return cp.getInterfaceMethodrefNameAndType(index); - else - return cp.getMethodrefNameAndType(index); + return cp.getMethodrefNameAndType(index); } /** * Returns the method or constructor containing the method-call * expression represented by this object. */ + @Override public CtBehavior where() { return super.where(); } /** @@ -55,6 +67,7 @@ public class MethodCall extends Expr { * * @return -1 if this information is not available. */ + @Override public int getLineNumber() { return super.getLineNumber(); } @@ -64,6 +77,7 @@ public class MethodCall extends Expr { * * @return null if this information is not available. */ + @Override public String getFileName() { return super.getFileName(); } @@ -137,6 +151,7 @@ public class MethodCall extends Expr { * including the expression can catch and the exceptions that * the throws declaration allows the method to throw. */ + @Override public CtClass[] mayThrow() { return super.mayThrow(); } @@ -176,6 +191,7 @@ public class MethodCall extends Expr { * * @param statement a Java statement except try-catch. */ + @Override public void replace(String statement) throws CannotCompileException { thisClass.getClassFile(); // to call checkModify(). ConstPool constPool = getConstPool(); diff --git a/src/main/javassist/expr/NewArray.java b/src/main/javassist/expr/NewArray.java index fe75a979..70d74afd 100644 --- a/src/main/javassist/expr/NewArray.java +++ b/src/main/javassist/expr/NewArray.java @@ -16,9 +16,24 @@ package javassist.expr; -import javassist.*; -import javassist.bytecode.*; -import javassist.compiler.*; +import javassist.CannotCompileException; +import javassist.CtBehavior; +import javassist.CtClass; +import javassist.CtPrimitiveType; +import javassist.NotFoundException; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; +import javassist.compiler.CompileError; +import javassist.compiler.Javac; +import javassist.compiler.JvstCodeGen; +import javassist.compiler.JvstTypeChecker; +import javassist.compiler.ProceedHandler; import javassist.compiler.ast.ASTList; /** @@ -40,6 +55,7 @@ public class NewArray extends Expr { * Returns the method or constructor containing the array creation * represented by this object. */ + @Override public CtBehavior where() { return super.where(); } /** @@ -48,6 +64,7 @@ public class NewArray extends Expr { * * @return -1 if this information is not available. */ + @Override public int getLineNumber() { return super.getLineNumber(); } @@ -57,6 +74,7 @@ public class NewArray extends Expr { * * @return null if this information is not available. */ + @Override public String getFileName() { return super.getFileName(); } @@ -67,6 +85,7 @@ public class NewArray extends Expr { * including the expression can catch and the exceptions that * the throws declaration allows the method to throw. */ + @Override public CtClass[] mayThrow() { return super.mayThrow(); } @@ -142,8 +161,7 @@ public class NewArray extends Expr { public int getCreatedDimensions() { if (opcode == Opcode.MULTIANEWARRAY) return iterator.byteAt(currentPos + 3); - else - return 1; + return 1; } /** @@ -156,6 +174,7 @@ public class NewArray extends Expr { * * @param statement a Java statement except try-catch. */ + @Override public void replace(String statement) throws CannotCompileException { try { replace2(statement); @@ -250,10 +269,11 @@ public class NewArray extends Expr { dimension = dim; } + @Override public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args) throws CompileError { - int num = gen.getMethodArgsLength(args); + int num = gen.getMethodArgsLength(args); if (num != dimension) throw new CompileError(Javac.proceedName + "() with a wrong number of parameters"); @@ -274,6 +294,7 @@ public class NewArray extends Expr { gen.setType(arrayType); } + @Override public void setReturnType(JvstTypeChecker c, ASTList args) throws CompileError { diff --git a/src/main/javassist/expr/NewExpr.java b/src/main/javassist/expr/NewExpr.java index 49c1ee49..6b28475b 100644 --- a/src/main/javassist/expr/NewExpr.java +++ b/src/main/javassist/expr/NewExpr.java @@ -16,9 +16,25 @@ package javassist.expr; -import javassist.*; -import javassist.bytecode.*; -import javassist.compiler.*; +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtBehavior; +import javassist.CtClass; +import javassist.CtConstructor; +import javassist.NotFoundException; +import javassist.bytecode.BadBytecode; +import javassist.bytecode.Bytecode; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.CodeIterator; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; +import javassist.compiler.CompileError; +import javassist.compiler.Javac; +import javassist.compiler.JvstCodeGen; +import javassist.compiler.JvstTypeChecker; +import javassist.compiler.ProceedHandler; import javassist.compiler.ast.ASTList; /** @@ -56,6 +72,7 @@ public class NewExpr extends Expr { * Returns the method or constructor containing the <tt>new</tt> * expression represented by this object. */ + @Override public CtBehavior where() { return super.where(); } /** @@ -64,6 +81,7 @@ public class NewExpr extends Expr { * * @return -1 if this information is not available. */ + @Override public int getLineNumber() { return super.getLineNumber(); } @@ -73,6 +91,7 @@ public class NewExpr extends Expr { * * @return null if this information is not available. */ + @Override public String getFileName() { return super.getFileName(); } @@ -123,6 +142,7 @@ public class NewExpr extends Expr { * including the expression can catch and the exceptions that * the throws declaration allows the method to throw. */ + @Override public CtClass[] mayThrow() { return super.mayThrow(); } @@ -160,6 +180,7 @@ public class NewExpr extends Expr { * * @param statement a Java statement except try-catch. */ + @Override public void replace(String statement) throws CannotCompileException { thisClass.getClassFile(); // to call checkModify(). @@ -228,6 +249,7 @@ public class NewExpr extends Expr { methodIndex = mi; } + @Override public void doit(JvstCodeGen gen, Bytecode bytecode, ASTList args) throws CompileError { @@ -239,6 +261,7 @@ public class NewExpr extends Expr { gen.setType(newType); } + @Override public void setReturnType(JvstTypeChecker c, ASTList args) throws CompileError { diff --git a/src/main/javassist/runtime/Cflow.java b/src/main/javassist/runtime/Cflow.java index d364abdb..0564747a 100644 --- a/src/main/javassist/runtime/Cflow.java +++ b/src/main/javassist/runtime/Cflow.java @@ -23,31 +23,32 @@ package javassist.runtime; * * @see javassist.CtBehavior#useCflow(String) */ -public class Cflow extends ThreadLocal { - private static class Depth { +public class Cflow extends ThreadLocal<Cflow.Depth> { + protected static class Depth { private int depth; Depth() { depth = 0; } - int get() { return depth; } + int value() { return depth; } void inc() { ++depth; } void dec() { --depth; } } - protected synchronized Object initialValue() { + @Override + protected synchronized Depth initialValue() { return new Depth(); } /** * Increments the counter. */ - public void enter() { ((Depth)get()).inc(); } + public void enter() { get().inc(); } /** * Decrements the counter. */ - public void exit() { ((Depth)get()).dec(); } + public void exit() { get().dec(); } /** * Returns the value of the counter. */ - public int value() { return ((Depth)get()).get(); } + public int value() { return get().value(); } } diff --git a/src/main/javassist/runtime/Desc.java b/src/main/javassist/runtime/Desc.java index 342bab12..c733b30d 100644 --- a/src/main/javassist/runtime/Desc.java +++ b/src/main/javassist/runtime/Desc.java @@ -34,20 +34,19 @@ public class Desc { */ public static boolean useContextClassLoader = false; - private static Class getClassObject(String name) + private static Class<?> getClassObject(String name) throws ClassNotFoundException { if (useContextClassLoader) return Class.forName(name, true, Thread.currentThread().getContextClassLoader()); - else - return Class.forName(name); + return Class.forName(name); } /** * Interprets the given class name. * It is used for implementing <code>$class</code>. */ - public static Class getClazz(String name) { + public static Class<?> getClazz(String name) { try { return getClassObject(name); } @@ -63,7 +62,7 @@ public class Desc { * Interprets the given type descriptor representing a method * signature. It is used for implementing <code>$sig</code>. */ - public static Class[] getParams(String desc) { + public static Class<?>[] getParams(String desc) { if (desc.charAt(0) != '(') throw new RuntimeException("$sig: internal error"); @@ -74,17 +73,17 @@ public class Desc { * Interprets the given type descriptor. * It is used for implementing <code>$type</code>. */ - public static Class getType(String desc) { - Class[] result = getType(desc, desc.length(), 0, 0); + public static Class<?> getType(String desc) { + Class<?>[] result = getType(desc, desc.length(), 0, 0); if (result == null || result.length != 1) throw new RuntimeException("$type: internal error"); return result[0]; } - private static Class[] getType(String desc, int descLen, + private static Class<?>[] getType(String desc, int descLen, int start, int num) { - Class clazz; + Class<?> clazz; if (start >= descLen) return new Class[num]; @@ -124,12 +123,12 @@ public class Desc { return new Class[num]; } - Class[] result = getType(desc, descLen, start + 1, num + 1); + Class<?>[] result = getType(desc, descLen, start + 1, num + 1); result[num] = clazz; return result; } - private static Class[] getClassType(String desc, int descLen, + private static Class<?>[] getClassType(String desc, int descLen, int start, int num) { int end = start; while (desc.charAt(end) == '[') @@ -147,7 +146,7 @@ public class Desc { else cname = desc.substring(start, end + 1); - Class[] result = getType(desc, descLen, end + 1, num + 1); + Class<?>[] result = getType(desc, descLen, end + 1, num + 1); try { result[num] = getClassObject(cname.replace('/', '.')); } diff --git a/src/main/javassist/tools/Callback.java b/src/main/javassist/tools/Callback.java index c3095ccb..c0c88094 100644 --- a/src/main/javassist/tools/Callback.java +++ b/src/main/javassist/tools/Callback.java @@ -16,12 +16,13 @@ package javassist.tools; -import javassist.CannotCompileException; -import javassist.CtBehavior; - import java.util.HashMap; +import java.util.Map; import java.util.UUID; +import javassist.CannotCompileException; +import javassist.CtBehavior; + /** * Creates bytecode that when executed calls back to the instance's result method. * @@ -49,7 +50,7 @@ import java.util.UUID; */ public abstract class Callback { - public static HashMap callbacks = new HashMap(); + public static Map<String,Callback> callbacks = new HashMap<String,Callback>(); private final String sourceCode; @@ -73,6 +74,7 @@ public abstract class Callback { */ public abstract void result(Object[] objects); + @Override public String toString(){ return sourceCode(); } diff --git a/src/main/javassist/tools/Dump.java b/src/main/javassist/tools/Dump.java index b22825e0..d6722713 100644 --- a/src/main/javassist/tools/Dump.java +++ b/src/main/javassist/tools/Dump.java @@ -16,7 +16,10 @@ package javassist.tools; -import java.io.*; +import java.io.DataInputStream; +import java.io.FileInputStream; +import java.io.PrintWriter; + import javassist.bytecode.ClassFile; import javassist.bytecode.ClassFilePrinter; diff --git a/src/main/javassist/tools/reflect/CannotCreateException.java b/src/main/javassist/tools/reflect/CannotCreateException.java index a6fbdc5e..83f92fc6 100644 --- a/src/main/javassist/tools/reflect/CannotCreateException.java +++ b/src/main/javassist/tools/reflect/CannotCreateException.java @@ -20,6 +20,9 @@ package javassist.tools.reflect; * Signals that <code>ClassMetaobject.newInstance()</code> fails. */ public class CannotCreateException extends Exception { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public CannotCreateException(String s) { super(s); } diff --git a/src/main/javassist/tools/reflect/CannotInvokeException.java b/src/main/javassist/tools/reflect/CannotInvokeException.java index e679a782..a9d05247 100644 --- a/src/main/javassist/tools/reflect/CannotInvokeException.java +++ b/src/main/javassist/tools/reflect/CannotInvokeException.java @@ -17,7 +17,6 @@ package javassist.tools.reflect; import java.lang.reflect.InvocationTargetException; -import java.lang.IllegalAccessException; /** * Thrown when method invocation using the reflection API has thrown @@ -29,6 +28,8 @@ import java.lang.IllegalAccessException; */ public class CannotInvokeException extends RuntimeException { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private Throwable err = null; /** diff --git a/src/main/javassist/tools/reflect/CannotReflectException.java b/src/main/javassist/tools/reflect/CannotReflectException.java index e6507c56..dc907107 100644 --- a/src/main/javassist/tools/reflect/CannotReflectException.java +++ b/src/main/javassist/tools/reflect/CannotReflectException.java @@ -17,6 +17,7 @@ package javassist.tools.reflect; import javassist.CannotCompileException; +import javassist.CtClass; /** * Thrown by <code>makeReflective()</code> in <code>Reflection</code> @@ -29,6 +30,9 @@ import javassist.CannotCompileException; * @see javassist.CannotCompileException */ public class CannotReflectException extends CannotCompileException { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public CannotReflectException(String msg) { super(msg); } diff --git a/src/main/javassist/tools/reflect/ClassMetaobject.java b/src/main/javassist/tools/reflect/ClassMetaobject.java index c958053f..a00622c5 100644 --- a/src/main/javassist/tools/reflect/ClassMetaobject.java +++ b/src/main/javassist/tools/reflect/ClassMetaobject.java @@ -16,12 +16,14 @@ package javassist.tools.reflect; -import java.lang.reflect.*; -import java.util.Arrays; -import java.io.Serializable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; /** * A runtime class metaobject. @@ -40,6 +42,8 @@ import java.io.ObjectOutputStream; * @see javassist.tools.reflect.Metalevel */ public class ClassMetaobject implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; /** * The base-level methods controlled by a metaobject * are renamed so that they begin with @@ -48,8 +52,8 @@ public class ClassMetaobject implements Serializable { static final String methodPrefix = "_m_"; static final int methodPrefixLen = 3; - private Class javaClass; - private Constructor[] constructors; + private Class<?> javaClass; + private Constructor<?>[] constructors; private Method[] methods; /** @@ -95,18 +99,17 @@ public class ClassMetaobject implements Serializable { methods = null; } - private Class getClassObject(String name) throws ClassNotFoundException { + private Class<?> getClassObject(String name) throws ClassNotFoundException { if (useContextClassLoader) return Thread.currentThread().getContextClassLoader() .loadClass(name); - else - return Class.forName(name); + return Class.forName(name); } /** * Obtains the <code>java.lang.Class</code> representing this class. */ - public final Class getJavaClass() { + public final Class<?> getJavaClass() { return javaClass; } @@ -162,7 +165,7 @@ public class ClassMetaobject implements Serializable { * <p>Every subclass of this class should redefine this method. */ public Object trapFieldRead(String name) { - Class jc = getJavaClass(); + Class<?> jc = getJavaClass(); try { return jc.getField(name).get(null); } @@ -182,7 +185,7 @@ public class ClassMetaobject implements Serializable { * <p>Every subclass of this class should redefine this method. */ public void trapFieldWrite(String name, Object value) { - Class jc = getJavaClass(); + Class<?> jc = getJavaClass(); try { jc.getField(name).set(null, value); } @@ -251,7 +254,7 @@ public class ClassMetaobject implements Serializable { if (methods != null) return methods; - Class baseclass = getJavaClass(); + Class<?> baseclass = getJavaClass(); Method[] allmethods = baseclass.getDeclaredMethods(); int n = allmethods.length; int[] index = new int[n]; @@ -320,7 +323,7 @@ public class ClassMetaobject implements Serializable { * formal parameter types of the method specified * by <code>identifier</code>. */ - public final Class[] getParameterTypes(int identifier) { + public final Class<?>[] getParameterTypes(int identifier) { return getReflectiveMethods()[identifier].getParameterTypes(); } @@ -328,7 +331,7 @@ public class ClassMetaobject implements Serializable { * Returns a <code>Class</code> objects representing the * return type of the method specified by <code>identifier</code>. */ - public final Class getReturnType(int identifier) { + public final Class<?> getReturnType(int identifier) { return getReflectiveMethods()[identifier].getReturnType(); } @@ -350,7 +353,7 @@ public class ClassMetaobject implements Serializable { * * @see ClassMetaobject#getMethod(int) */ - public final int getMethodIndex(String originalName, Class[] argTypes) + public final int getMethodIndex(String originalName, Class<?>[] argTypes) throws NoSuchMethodException { Method[] mthds = getReflectiveMethods(); diff --git a/src/main/javassist/tools/reflect/Compiler.java b/src/main/javassist/tools/reflect/Compiler.java index 3114fd89..b919684b 100644 --- a/src/main/javassist/tools/reflect/Compiler.java +++ b/src/main/javassist/tools/reflect/Compiler.java @@ -16,10 +16,11 @@ package javassist.tools.reflect; -import javassist.CtClass; -import javassist.ClassPool; import java.io.PrintStream; +import javassist.ClassPool; +import javassist.CtClass; + class CompiledClass { public String classname; public String metaobject; diff --git a/src/main/javassist/tools/reflect/Loader.java b/src/main/javassist/tools/reflect/Loader.java index ad4dfa55..f144877f 100644 --- a/src/main/javassist/tools/reflect/Loader.java +++ b/src/main/javassist/tools/reflect/Loader.java @@ -17,8 +17,8 @@ package javassist.tools.reflect; import javassist.CannotCompileException; -import javassist.NotFoundException; import javassist.ClassPool; +import javassist.NotFoundException; /** * A class loader for reflection. diff --git a/src/main/javassist/tools/reflect/Metaobject.java b/src/main/javassist/tools/reflect/Metaobject.java index 91a6126e..d3adcb13 100644 --- a/src/main/javassist/tools/reflect/Metaobject.java +++ b/src/main/javassist/tools/reflect/Metaobject.java @@ -16,11 +16,11 @@ package javassist.tools.reflect; -import java.lang.reflect.Method; -import java.io.Serializable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.lang.reflect.Method; /** * A runtime metaobject. @@ -45,6 +45,8 @@ import java.io.ObjectOutputStream; * @see javassist.tools.reflect.Metalevel */ public class Metaobject implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; protected ClassMetaobject classmetaobject; protected Metalevel baseobject; protected Method[] methods; @@ -138,7 +140,7 @@ public class Metaobject implements Serializable { * formal parameter types of the method specified * by <code>identifier</code>. */ - public final Class[] getParameterTypes(int identifier) { + public final Class<?>[] getParameterTypes(int identifier) { return methods[identifier].getParameterTypes(); } @@ -146,7 +148,7 @@ public class Metaobject implements Serializable { * Returns a <code>Class</code> objects representing the * return type of the method specified by <code>identifier</code>. */ - public final Class getReturnType(int identifier) { + public final Class<?> getReturnType(int identifier) { return methods[identifier].getReturnType(); } @@ -158,7 +160,7 @@ public class Metaobject implements Serializable { * <p>Every subclass of this class should redefine this method. */ public Object trapFieldRead(String name) { - Class jc = getClassMetaobject().getJavaClass(); + Class<?> jc = getClassMetaobject().getJavaClass(); try { return jc.getField(name).get(getObject()); } @@ -178,7 +180,7 @@ public class Metaobject implements Serializable { * <p>Every subclass of this class should redefine this method. */ public void trapFieldWrite(String name, Object value) { - Class jc = getClassMetaobject().getJavaClass(); + Class<?> jc = getClassMetaobject().getJavaClass(); try { jc.getField(name).set(getObject(), value); } diff --git a/src/main/javassist/tools/reflect/Reflection.java b/src/main/javassist/tools/reflect/Reflection.java index 406ce3d5..dddd9a41 100644 --- a/src/main/javassist/tools/reflect/Reflection.java +++ b/src/main/javassist/tools/reflect/Reflection.java @@ -16,11 +16,19 @@ package javassist.tools.reflect; -import java.util.Iterator; -import javassist.*; +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CodeConverter; +import javassist.CtClass; +import javassist.CtField; +import javassist.CtMethod; import javassist.CtMethod.ConstParameter; -import javassist.bytecode.ClassFile; +import javassist.CtNewMethod; +import javassist.Modifier; +import javassist.NotFoundException; +import javassist.Translator; import javassist.bytecode.BadBytecode; +import javassist.bytecode.ClassFile; import javassist.bytecode.MethodInfo; /** @@ -105,6 +113,7 @@ public class Reflection implements Translator { /** * Initializes the object. */ + @Override public void start(ClassPool pool) throws NotFoundException { classPool = pool; final String msg @@ -130,6 +139,7 @@ public class Reflection implements Translator { * Inserts hooks for intercepting accesses to the fields declared * in reflective classes. */ + @Override public void onLoad(ClassPool pool, String classname) throws CannotCompileException, NotFoundException { @@ -176,8 +186,8 @@ public class Reflection implements Translator { * @see javassist.tools.reflect.Metaobject * @see javassist.tools.reflect.ClassMetaobject */ - public boolean makeReflective(Class clazz, - Class metaobject, Class metaclass) + public boolean makeReflective(Class<?> clazz, + Class<?> metaobject, Class<?> metaclass) throws CannotCompileException, NotFoundException { return makeReflective(clazz.getName(), metaobject.getName(), @@ -248,8 +258,7 @@ public class Reflection implements Translator { { if (clazz.getAttribute("Reflective") != null) return false; // this is already reflective. - else - clazz.setAttribute("Reflective", new byte[0]); + clazz.setAttribute("Reflective", new byte[0]); CtClass mlevel = classPool.get("javassist.tools.reflect.Metalevel"); boolean addMeta = !clazz.subtypeOf(mlevel); @@ -394,10 +403,7 @@ public class Reflection implements Translator { if (ClassFile.MAJOR_VERSION < ClassFile.JAVA_6) return; - Iterator methods = cf.getMethods().iterator(); - while (methods.hasNext()) { - MethodInfo mi = (MethodInfo)methods.next(); + for (MethodInfo mi:cf.getMethods()) mi.rebuildStackMap(classPool); - } } } diff --git a/src/main/javassist/tools/reflect/Sample.java b/src/main/javassist/tools/reflect/Sample.java index b4634ec7..8a7360db 100644 --- a/src/main/javassist/tools/reflect/Sample.java +++ b/src/main/javassist/tools/reflect/Sample.java @@ -28,8 +28,7 @@ public class Sample { mobj = _metaobject; if (mobj == null) return ClassMetaobject.invoke(this, identifier, args); - else - return mobj.trapMethodcall(identifier, args); + return mobj.trapMethodcall(identifier, args); } public static Object trapStatic(Object[] args, int identifier) @@ -41,8 +40,7 @@ public class Sample { public static Object trapRead(Object[] args, String name) { if (args[0] == null) return _classobject.trapFieldRead(name); - else - return ((Metalevel)args[0])._getMetaobject().trapFieldRead(name); + return ((Metalevel)args[0])._getMetaobject().trapFieldRead(name); } public static Object trapWrite(Object[] args, String name) { diff --git a/src/main/javassist/tools/rmi/AppletServer.java b/src/main/javassist/tools/rmi/AppletServer.java index cc348ac2..e49ed0dc 100644 --- a/src/main/javassist/tools/rmi/AppletServer.java +++ b/src/main/javassist/tools/rmi/AppletServer.java @@ -16,16 +16,26 @@ package javassist.tools.rmi; -import java.io.*; - -import javassist.tools.web.*; -import javassist.CannotCompileException; -import javassist.NotFoundException; -import javassist.ClassPool; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InvalidClassException; +import java.io.NotSerializableException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; import java.lang.reflect.Method; import java.util.Hashtable; +import java.util.List; +import java.util.Map; import java.util.Vector; +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.NotFoundException; +import javassist.tools.web.BadHttpRequest; +import javassist.tools.web.Webserver; + /** * An AppletServer object is a web server that an ObjectImporter * communicates with. It makes the objects specified by @@ -37,8 +47,8 @@ import java.util.Vector; */ public class AppletServer extends Webserver { private StubGenerator stubGen; - private Hashtable exportedNames; - private Vector exportedObjects; + private Map<String,ExportedObject> exportedNames; + private List<ExportedObject> exportedObjects; private static final byte[] okHeader = "HTTP/1.0 200 OK\r\n\r\n".getBytes(); @@ -81,8 +91,8 @@ public class AppletServer extends Webserver { throws IOException, NotFoundException, CannotCompileException { super(port); - exportedNames = new Hashtable(); - exportedObjects = new Vector(); + exportedNames = new Hashtable<String,ExportedObject>(); + exportedObjects = new Vector<ExportedObject>(); stubGen = gen; addTranslator(loader, gen); } @@ -90,6 +100,7 @@ public class AppletServer extends Webserver { /** * Begins the HTTP service. */ + @Override public void run() { super.run(); } @@ -109,11 +120,11 @@ public class AppletServer extends Webserver { public synchronized int exportObject(String name, Object obj) throws CannotCompileException { - Class clazz = obj.getClass(); + Class<?> clazz = obj.getClass(); ExportedObject eo = new ExportedObject(); eo.object = obj; eo.methods = clazz.getMethods(); - exportedObjects.addElement(eo); + exportedObjects.add(eo); eo.identifier = exportedObjects.size() - 1; if (name != null) exportedNames.put(name, eo); @@ -131,6 +142,7 @@ public class AppletServer extends Webserver { /** * Processes a request from a web browser (an ObjectImporter). */ + @Override public void doReply(InputStream in, OutputStream out, String cmd) throws IOException, BadHttpRequest { @@ -152,8 +164,7 @@ public class AppletServer extends Webserver { Exception err = null; Object rvalue = null; try { - ExportedObject eo - = (ExportedObject)exportedObjects.elementAt(objectId); + ExportedObject eo = exportedObjects.get(objectId); Object[] args = readParameters(in); rvalue = convertRvalue(eo.methods[methodId].invoke(eo.object, args)); @@ -195,8 +206,7 @@ public class AppletServer extends Webserver { Object a = in.readObject(); if (a instanceof RemoteRef) { RemoteRef ref = (RemoteRef)a; - ExportedObject eo - = (ExportedObject)exportedObjects.elementAt(ref.oid); + ExportedObject eo = exportedObjects.get(ref.oid); a = eo.object; } @@ -215,8 +225,7 @@ public class AppletServer extends Webserver { String classname = rvalue.getClass().getName(); if (stubGen.isProxyClass(classname)) return new RemoteRef(exportObject(null, rvalue), classname); - else - return rvalue; + return rvalue; } private void lookupName(String cmd, InputStream ins, OutputStream outs) @@ -224,7 +233,7 @@ public class AppletServer extends Webserver { { ObjectInputStream in = new ObjectInputStream(ins); String name = DataInputStream.readUTF(in); - ExportedObject found = (ExportedObject)exportedNames.get(name); + ExportedObject found = exportedNames.get(name); outs.write(okHeader); ObjectOutputStream out = new ObjectOutputStream(outs); if (found == null) { diff --git a/src/main/javassist/tools/rmi/ObjectImporter.java b/src/main/javassist/tools/rmi/ObjectImporter.java index 43b62039..798279af 100644 --- a/src/main/javassist/tools/rmi/ObjectImporter.java +++ b/src/main/javassist/tools/rmi/ObjectImporter.java @@ -16,10 +16,16 @@ package javassist.tools.rmi; -import java.io.*; -import java.net.*; -import java.applet.Applet; -import java.lang.reflect.*; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; +import java.lang.reflect.Constructor; +import java.net.Socket; +import java.net.URL; /** * The object importer enables applets to call a method on a remote @@ -73,6 +79,8 @@ import java.lang.reflect.*; * @see javassist.tools.web.Viewer */ public class ObjectImporter implements java.io.Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private final byte[] endofline = { 0x0d, 0x0a }; private String servername, orgServername; private int port, orgPort; @@ -88,7 +96,8 @@ public class ObjectImporter implements java.io.Serializable { * * @param applet the applet loaded from the <code>Webserver</code>. */ - public ObjectImporter(Applet applet) { + public ObjectImporter(@SuppressWarnings("deprecation") java.applet.Applet applet) { + @SuppressWarnings("deprecation") URL codebase = applet.getCodeBase(); orgServername = servername = codebase.getHost(); orgPort = port = codebase.getPort(); @@ -183,12 +192,12 @@ public class ObjectImporter implements java.io.Serializable { throw new ObjectNotFoundException(name); } - private static final Class[] proxyConstructorParamTypes + private static final Class<?>[] proxyConstructorParamTypes = new Class[] { ObjectImporter.class, int.class }; private Object createProxy(int oid, String classname) throws Exception { - Class c = Class.forName(classname); - Constructor cons = c.getConstructor(proxyConstructorParamTypes); + Class<?> c = Class.forName(classname); + Constructor<?> cons = c.getConstructor(proxyConstructorParamTypes); return cons.newInstance(new Object[] { this, Integer.valueOf(oid) }); } @@ -267,8 +276,7 @@ public class ObjectImporter implements java.io.Serializable { if (result) return rvalue; - else - throw new RemoteException(errmsg); + throw new RemoteException(errmsg); } private void skipHeader(InputStream in) throws IOException { diff --git a/src/main/javassist/tools/rmi/ObjectNotFoundException.java b/src/main/javassist/tools/rmi/ObjectNotFoundException.java index 47cfb68e..bd5b27eb 100644 --- a/src/main/javassist/tools/rmi/ObjectNotFoundException.java +++ b/src/main/javassist/tools/rmi/ObjectNotFoundException.java @@ -17,6 +17,9 @@ package javassist.tools.rmi; public class ObjectNotFoundException extends Exception { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public ObjectNotFoundException(String name) { super(name + " is not exported"); } diff --git a/src/main/javassist/tools/rmi/RemoteException.java b/src/main/javassist/tools/rmi/RemoteException.java index e00dff59..6d4612a7 100644 --- a/src/main/javassist/tools/rmi/RemoteException.java +++ b/src/main/javassist/tools/rmi/RemoteException.java @@ -21,6 +21,9 @@ package javassist.tools.rmi; * during remote method invocation. */ public class RemoteException extends RuntimeException { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public RemoteException(String msg) { super(msg); } diff --git a/src/main/javassist/tools/rmi/RemoteRef.java b/src/main/javassist/tools/rmi/RemoteRef.java index 6b604bc5..4537352e 100644 --- a/src/main/javassist/tools/rmi/RemoteRef.java +++ b/src/main/javassist/tools/rmi/RemoteRef.java @@ -21,6 +21,8 @@ package javassist.tools.rmi; * reference through a network stream. */ public class RemoteRef implements java.io.Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; public int oid; public String classname; diff --git a/src/main/javassist/tools/rmi/StubGenerator.java b/src/main/javassist/tools/rmi/StubGenerator.java index 6fc8dbcf..b0817ab5 100644 --- a/src/main/javassist/tools/rmi/StubGenerator.java +++ b/src/main/javassist/tools/rmi/StubGenerator.java @@ -16,10 +16,22 @@ package javassist.tools.rmi; -import javassist.*; import java.lang.reflect.Method; import java.util.Hashtable; +import java.util.Map; + +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtConstructor; +import javassist.CtField; +import javassist.CtMethod; import javassist.CtMethod.ConstParameter; +import javassist.CtNewConstructor; +import javassist.CtNewMethod; +import javassist.Modifier; +import javassist.NotFoundException; +import javassist.Translator; /** * A stub-code generator. It is used for producing a proxy class. @@ -47,7 +59,7 @@ public class StubGenerator implements Translator { private static final String sampleClass = "javassist.tools.rmi.Sample"; private ClassPool classPool; - private Hashtable proxyClasses; + private Map<String,CtClass> proxyClasses; private CtMethod forwardMethod; private CtMethod forwardStaticMethod; @@ -59,7 +71,7 @@ public class StubGenerator implements Translator { * Constructs a stub-code generator. */ public StubGenerator() { - proxyClasses = new Hashtable(); + proxyClasses = new Hashtable<String,CtClass>(); } /** @@ -68,6 +80,7 @@ public class StubGenerator implements Translator { * * @see javassist.Translator#start(ClassPool) */ + @Override public void start(ClassPool pool) throws NotFoundException { classPool = pool; CtClass c = pool.get(sampleClass); @@ -89,6 +102,7 @@ public class StubGenerator implements Translator { * This is a method declared in javassist.Translator. * @see javassist.Translator#onLoad(ClassPool,String) */ + @Override public void onLoad(ClassPool pool, String classname) {} /** @@ -110,22 +124,20 @@ public class StubGenerator implements Translator { * @return <code>false</code> if the proxy class * has been already produced. */ - public synchronized boolean makeProxyClass(Class clazz) + public synchronized boolean makeProxyClass(Class<?> clazz) throws CannotCompileException, NotFoundException { String classname = clazz.getName(); if (proxyClasses.get(classname) != null) return false; - else { - CtClass ctclazz = produceProxyClass(classPool.get(classname), - clazz); - proxyClasses.put(classname, ctclazz); - modifySuperclass(ctclazz); - return true; - } + CtClass ctclazz = produceProxyClass(classPool.get(classname), + clazz); + proxyClasses.put(classname, ctclazz); + modifySuperclass(ctclazz); + return true; } - private CtClass produceProxyClass(CtClass orgclass, Class orgRtClass) + private CtClass produceProxyClass(CtClass orgclass, Class<?> orgRtClass) throws CannotCompileException, NotFoundException { int modify = orgclass.getModifiers(); @@ -166,7 +178,7 @@ public class StubGenerator implements Translator { } } - private CtClass toCtClass(Class rtclass) throws NotFoundException { + private CtClass toCtClass(Class<?> rtclass) throws NotFoundException { String name; if (!rtclass.isArray()) name = rtclass.getName(); @@ -179,11 +191,11 @@ public class StubGenerator implements Translator { sbuf.insert(0, rtclass.getName()); name = sbuf.toString(); } - + return classPool.get(name); } - private CtClass[] toCtClass(Class[] rtclasses) throws NotFoundException { + private CtClass[] toCtClass(Class<?>[] rtclasses) throws NotFoundException { int n = rtclasses.length; CtClass[] ctclasses = new CtClass[n]; for (int i = 0; i < n; ++i) diff --git a/src/main/javassist/tools/web/BadHttpRequest.java b/src/main/javassist/tools/web/BadHttpRequest.java index 0eaa266c..52ef4f5b 100644 --- a/src/main/javassist/tools/web/BadHttpRequest.java +++ b/src/main/javassist/tools/web/BadHttpRequest.java @@ -20,16 +20,18 @@ package javassist.tools.web; * Thrown when receiving an invalid HTTP request. */ public class BadHttpRequest extends Exception { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private Exception e; public BadHttpRequest() { e = null; } public BadHttpRequest(Exception _e) { e = _e; } + @Override public String toString() { if (e == null) return super.toString(); - else - return e.toString(); + return e.toString(); } } diff --git a/src/main/javassist/tools/web/Viewer.java b/src/main/javassist/tools/web/Viewer.java index 69fe3536..8fb015f7 100644 --- a/src/main/javassist/tools/web/Viewer.java +++ b/src/main/javassist/tools/web/Viewer.java @@ -16,8 +16,10 @@ package javassist.tools.web; -import java.io.*; -import java.net.*; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; /** * A sample applet viewer. @@ -97,7 +99,7 @@ public class Viewer extends ClassLoader { public void run(String classname, String[] args) throws Throwable { - Class c = loadClass(classname); + Class<?> c = loadClass(classname); try { c.getDeclaredMethod("main", new Class[] { String[].class }) .invoke(null, new Object[] { args }); @@ -110,10 +112,11 @@ public class Viewer extends ClassLoader { /** * Requests the class loader to load a class. */ - protected synchronized Class loadClass(String name, boolean resolve) + @Override + protected synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { - Class c = findLoadedClass(name); + Class<?> c = findLoadedClass(name); if (c == null) c = findClass(name); @@ -136,8 +139,9 @@ public class Viewer extends ClassLoader { * <p>This method can be overridden by a subclass of * <code>Viewer</code>. */ - protected Class findClass(String name) throws ClassNotFoundException { - Class c = null; + @Override + protected Class<?> findClass(String name) throws ClassNotFoundException { + Class<?> c = null; if (name.startsWith("java.") || name.startsWith("javax.") || name.equals("javassist.tools.web.Viewer")) c = findSystemClass(name); diff --git a/src/main/javassist/tools/web/Webserver.java b/src/main/javassist/tools/web/Webserver.java index 59ef9c2b..d90e8e34 100644 --- a/src/main/javassist/tools/web/Webserver.java +++ b/src/main/javassist/tools/web/Webserver.java @@ -16,10 +16,23 @@ package javassist.tools.web; -import java.net.*; -import java.io.*; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; import java.util.Date; -import javassist.*; + +import javassist.CannotCompileException; +import javassist.ClassPool; +import javassist.CtClass; +import javassist.NotFoundException; +import javassist.Translator; /** * A web server for running sample programs. @@ -278,8 +291,7 @@ public class Webserver { len = fin.read(filebuffer); if (len <= 0) break; - else - out.write(filebuffer, 0, len); + out.write(filebuffer, 0, len); } fin.close(); @@ -299,8 +311,7 @@ public class Webserver { len = fin.read(filebuffer); if (len <= 0) break; - else - barray.write(filebuffer, 0, len); + barray.write(filebuffer, 0, len); } byte[] classfile = barray.toByteArray(); @@ -398,6 +409,7 @@ class ServiceThread extends Thread { sock = s; } + @Override public void run() { try { web.process(sock); diff --git a/src/main/javassist/util/HotSwapAgent.java b/src/main/javassist/util/HotSwapAgent.java index 684f8540..e696ce22 100644 --- a/src/main/javassist/util/HotSwapAgent.java +++ b/src/main/javassist/util/HotSwapAgent.java @@ -21,11 +21,12 @@ import java.io.IOException; import java.lang.instrument.ClassDefinition; import java.lang.instrument.Instrumentation; import java.lang.instrument.UnmodifiableClassException; +import java.lang.management.ManagementFactory; import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; -import java.lang.management.ManagementFactory; + import com.sun.tools.attach.VirtualMachine; import javassist.CannotCompileException; @@ -106,10 +107,10 @@ public class HotSwapAgent { /** * Redefines a class. */ - public static void redefine(Class oldClass, CtClass newClass) + public static void redefine(Class<?> oldClass, CtClass newClass) throws NotFoundException, IOException, CannotCompileException { - Class[] old = { oldClass }; + Class<?>[] old = { oldClass }; CtClass[] newClasses = { newClass }; redefine(old, newClasses); } @@ -117,7 +118,7 @@ public class HotSwapAgent { /** * Redefines classes. */ - public static void redefine(Class[] oldClasses, CtClass[] newClasses) + public static void redefine(Class<?>[] oldClasses, CtClass[] newClasses) throws NotFoundException, IOException, CannotCompileException { startAgent(); diff --git a/src/main/javassist/util/HotSwapper.java b/src/main/javassist/util/HotSwapper.java index f47c3285..5d64ee5c 100644 --- a/src/main/javassist/util/HotSwapper.java +++ b/src/main/javassist/util/HotSwapper.java @@ -16,12 +16,25 @@ package javassist.util; -import com.sun.jdi.*; -import com.sun.jdi.connect.*; -import com.sun.jdi.event.*; -import com.sun.jdi.request.*; -import java.io.*; -import java.util.*; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.sun.jdi.Bootstrap; +import com.sun.jdi.ReferenceType; +import com.sun.jdi.VirtualMachine; +import com.sun.jdi.connect.AttachingConnector; +import com.sun.jdi.connect.Connector; +import com.sun.jdi.connect.IllegalConnectorArgumentsException; +import com.sun.jdi.event.Event; +import com.sun.jdi.event.EventIterator; +import com.sun.jdi.event.EventQueue; +import com.sun.jdi.event.EventSet; +import com.sun.jdi.event.MethodEntryEvent; +import com.sun.jdi.request.EventRequest; +import com.sun.jdi.request.EventRequestManager; +import com.sun.jdi.request.MethodEntryRequest; class Trigger { void doSwap() {} @@ -80,7 +93,7 @@ class Trigger { public class HotSwapper { private VirtualMachine jvm; private MethodEntryRequest request; - private Map newClassFiles; + private Map<ReferenceType,byte[]> newClassFiles; private Trigger trigger; @@ -113,23 +126,20 @@ public class HotSwapper { AttachingConnector connector = (AttachingConnector)findConnector("com.sun.jdi.SocketAttach"); - Map arguments = connector.defaultArguments(); - ((Connector.Argument)arguments.get("hostname")).setValue(HOST_NAME); - ((Connector.Argument)arguments.get("port")).setValue(port); + Map<String,Connector.Argument> arguments = connector.defaultArguments(); + arguments.get("hostname").setValue(HOST_NAME); + arguments.get("port").setValue(port); jvm = connector.attach(arguments); EventRequestManager manager = jvm.eventRequestManager(); request = methodEntryRequests(manager, TRIGGER_NAME); } private Connector findConnector(String connector) throws IOException { - List connectors = Bootstrap.virtualMachineManager().allConnectors(); - Iterator iter = connectors.iterator(); - while (iter.hasNext()) { - Connector con = (Connector)iter.next(); - if (con.name().equals(connector)) { + List<Connector> connectors = Bootstrap.virtualMachineManager().allConnectors(); + + for (Connector con:connectors) + if (con.name().equals(connector)) return con; - } - } throw new IOException("Not found: " + connector); } @@ -145,6 +155,7 @@ public class HotSwapper { /* Stops triggering a hotswapper when reload() is called. */ + @SuppressWarnings("unused") private void deleteEventRequest(EventRequestManager manager, MethodEntryRequest request) { manager.deleteEventRequest(request); @@ -158,7 +169,7 @@ public class HotSwapper { */ public void reload(String className, byte[] classFile) { ReferenceType classtype = toRefType(className); - Map map = new HashMap(); + Map<ReferenceType,byte[]> map = new HashMap<ReferenceType,byte[]>(); map.put(classtype, classFile); reload2(map, className); } @@ -171,14 +182,11 @@ public class HotSwapper { * is <code>String</code> and the type of the * class files is <code>byte[]</code>. */ - public void reload(Map classFiles) { - Set set = classFiles.entrySet(); - Iterator it = set.iterator(); - Map map = new HashMap(); + public void reload(Map<String,byte[]> classFiles) { + Map<ReferenceType,byte[]> map = new HashMap<ReferenceType,byte[]>(); String className = null; - while (it.hasNext()) { - Map.Entry e = (Map.Entry)it.next(); - className = (String)e.getKey(); + for (Map.Entry<String,byte[]> e:classFiles.entrySet()) { + className = e.getKey(); map.put(toRefType(className), e.getValue()); } @@ -187,21 +195,20 @@ public class HotSwapper { } private ReferenceType toRefType(String className) { - List list = jvm.classesByName(className); + List<ReferenceType> list = jvm.classesByName(className); if (list == null || list.isEmpty()) throw new RuntimeException("no such class: " + className); - else - return (ReferenceType)list.get(0); + return list.get(0); } - private void reload2(Map map, String msg) { + private void reload2(Map<ReferenceType,byte[]> map, String msg) { synchronized (trigger) { startDaemon(); newClassFiles = map; request.enable(); trigger.doSwap(); request.disable(); - Map ncf = newClassFiles; + Map<ReferenceType,byte[]> ncf = newClassFiles; if (ncf != null) { newClassFiles = null; throw new RuntimeException("failed to reload: " + msg); @@ -216,6 +223,7 @@ public class HotSwapper { e.printStackTrace(System.err); } + @Override public void run() { EventSet events = null; try { @@ -249,7 +257,7 @@ public class HotSwapper { } void hotswap() { - Map map = newClassFiles; + Map<ReferenceType,byte[]> map = newClassFiles; jvm.redefineClasses(map); newClassFiles = null; } diff --git a/src/main/javassist/util/proxy/FactoryHelper.java b/src/main/javassist/util/proxy/FactoryHelper.java index 34af79d3..1fb63b65 100644 --- a/src/main/javassist/util/proxy/FactoryHelper.java +++ b/src/main/javassist/util/proxy/FactoryHelper.java @@ -39,11 +39,9 @@ public class FactoryHelper { * * @throws RuntimeException if a given type is not a primitive type. */ - public static final int typeIndex(Class type) { - Class[] list = primitiveTypes; - int n = list.length; - for (int i = 0; i < n; i++) - if (list[i] == type) + public static final int typeIndex(Class<?> type) { + for (int i = 0; i < primitiveTypes.length; i++) + if (primitiveTypes[i] == type) return i; throw new RuntimeException("bad type:" + type.getName()); @@ -52,7 +50,7 @@ public class FactoryHelper { /** * <code>Class</code> objects representing primitive types. */ - public static final Class[] primitiveTypes = { + public static final Class<?>[] primitiveTypes = { Boolean.TYPE, Byte.TYPE, Character.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE, Void.TYPE }; @@ -108,7 +106,7 @@ public class FactoryHelper { * * @see #toClass(ClassFile,ClassLoader,ProtectionDomain) */ - public static Class toClass(ClassFile cf, ClassLoader loader) + public static Class<?> toClass(ClassFile cf, ClassLoader loader) throws CannotCompileException { return toClass(cf, loader, null); @@ -120,15 +118,14 @@ public class FactoryHelper { * @param domain if it is null, a default domain is used. * @since 3.3 */ - public static Class toClass(ClassFile cf, ClassLoader loader, ProtectionDomain domain) + public static Class<?> toClass(ClassFile cf, ClassLoader loader, ProtectionDomain domain) throws CannotCompileException { try { byte[] b = toBytecode(cf); if (ProxyFactory.onlyPublicMethods) return DefineClassHelper.toPublicClass(cf.getName(), b); - else - return DefineClassHelper.toClass(cf.getName(), loader, domain, b); + return DefineClassHelper.toClass(cf.getName(), loader, domain, b); } catch (IOException e) { throw new CannotCompileException(e); diff --git a/src/main/javassist/util/proxy/ProxyFactory.java b/src/main/javassist/util/proxy/ProxyFactory.java index 35c6c11e..072fb42c 100644 --- a/src/main/javassist/util/proxy/ProxyFactory.java +++ b/src/main/javassist/util/proxy/ProxyFactory.java @@ -16,18 +16,39 @@ package javassist.util.proxy; +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; +import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Constructor; import java.lang.reflect.Member; +import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.ProtectionDomain; -import java.util.*; -import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.WeakHashMap; import javassist.CannotCompileException; -import javassist.bytecode.*; +import javassist.bytecode.AccessFlag; +import javassist.bytecode.Bytecode; +import javassist.bytecode.ClassFile; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.ConstPool; +import javassist.bytecode.Descriptor; +import javassist.bytecode.DuplicateMemberException; +import javassist.bytecode.ExceptionsAttribute; +import javassist.bytecode.FieldInfo; +import javassist.bytecode.MethodInfo; +import javassist.bytecode.Opcode; +import javassist.bytecode.StackMapTable; /* * This class is implemented only with the lower-level API of Javassist. @@ -153,17 +174,17 @@ import javassist.bytecode.*; * @author Andrew Dinn */ public class ProxyFactory { - private Class superClass; - private Class[] interfaces; + private Class<?> superClass; + private Class<?>[] interfaces; private MethodFilter methodFilter; private MethodHandler handler; // retained for legacy usage - private List signatureMethods; + private List<Map.Entry<String,Method>> signatureMethods; private boolean hasGetHandler; private byte[] signature; private String classname; private String basename; private String superName; - private Class thisClass; + private Class<?> thisClass; /** * per factory setting initialised from current setting for useCache but able to be reset before each create call */ @@ -208,7 +229,7 @@ public class ProxyFactory { */ public String writeDirectory; - private static final Class OBJECT_TYPE = Object.class; + private static final Class<?> OBJECT_TYPE = Object.class; private static final String HOLDER = "_methods_"; private static final String HOLDER_TYPE = "[Ljava/lang/reflect/Method;"; @@ -310,14 +331,15 @@ public class ProxyFactory { factoryWriteReplace = useWriteReplace; } - private static WeakHashMap proxyCache = new WeakHashMap(); + private static Map<ClassLoader,Map<String,ProxyDetails>> proxyCache = + new WeakHashMap<ClassLoader,Map<String,ProxyDetails>>(); /** * determine if a class is a javassist proxy class * @param cl * @return true if the class is a javassist proxy class otherwise false */ - public static boolean isProxyClass(Class cl) + public static boolean isProxyClass(Class<?> cl) { // all proxies implement Proxy or ProxyObject. nothing else should. return (Proxy.class.isAssignableFrom(cl)); @@ -339,17 +361,17 @@ public class ProxyFactory { * a hexadecimal string representation of the signature bit sequence. this string also forms part * of the proxy class name. */ - WeakReference proxyClass; + Reference<Class<?>> proxyClass; /** * a flag which is true this class employs writeReplace to perform serialization of its instances * and false if serialization must employ of a ProxyObjectOutputStream and ProxyObjectInputStream */ boolean isUseWriteReplace; - ProxyDetails(byte[] signature, Class proxyClass, boolean isUseWriteReplace) + ProxyDetails(byte[] signature, Class<?> proxyClass, boolean isUseWriteReplace) { this.signature = signature; - this.proxyClass = new WeakReference(proxyClass); + this.proxyClass = new WeakReference<Class<?>>(proxyClass); this.isUseWriteReplace = isUseWriteReplace; } } @@ -374,7 +396,7 @@ public class ProxyFactory { /** * Sets the super class of a proxy class. */ - public void setSuperclass(Class clazz) { + public void setSuperclass(Class<?> clazz) { superClass = clazz; // force recompute of signature signature = null; @@ -385,12 +407,12 @@ public class ProxyFactory { * * @since 3.4 */ - public Class getSuperclass() { return superClass; } + public Class<?> getSuperclass() { return superClass; } /** * Sets the interfaces of a proxy class. */ - public void setInterfaces(Class[] ifs) { + public void setInterfaces(Class<?>[] ifs) { interfaces = ifs; // force recompute of signature signature = null; @@ -401,7 +423,7 @@ public class ProxyFactory { * * @since 3.4 */ - public Class[] getInterfaces() { return interfaces; } + public Class<?>[] getInterfaces() { return interfaces; } /** * Sets a filter that selects the methods that will be controlled by a handler. @@ -415,7 +437,7 @@ public class ProxyFactory { /** * Generates a proxy class using the current filter. */ - public Class createClass() { + public Class<?> createClass() { if (signature == null) { computeSignature(methodFilter); } @@ -425,7 +447,7 @@ public class ProxyFactory { /** * Generates a proxy class using the supplied filter. */ - public Class createClass(MethodFilter filter) { + public Class<?> createClass(MethodFilter filter) { computeSignature(filter); return createClass1(); } @@ -436,20 +458,20 @@ public class ProxyFactory { * @param signature * @return */ - Class createClass(byte[] signature) + Class<?> createClass(byte[] signature) { installSignature(signature); return createClass1(); } - private Class createClass1() { - Class result = thisClass; + private Class<?> createClass1() { + Class<?> result = thisClass; if (result == null) { ClassLoader cl = getClassLoader(); synchronized (proxyCache) { if (factoryUseCache) createClass2(cl); - else + else createClass3(cl); result = thisClass; @@ -465,7 +487,7 @@ public class ProxyFactory { { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - public String getKey(Class superClass, Class[] interfaces, byte[] signature, boolean useWriteReplace) + public String getKey(Class<?> superClass, Class<?>[] interfaces, byte[] signature, boolean useWriteReplace) { StringBuffer sbuf = new StringBuffer(); if (superClass != null){ @@ -498,16 +520,16 @@ public class ProxyFactory { * reducing concrrency. */ // synchronized (proxyCache) { - HashMap cacheForTheLoader = (HashMap)proxyCache.get(cl); + Map<String,ProxyDetails> cacheForTheLoader = proxyCache.get(cl); ProxyDetails details; if (cacheForTheLoader == null) { - cacheForTheLoader = new HashMap(); + cacheForTheLoader = new HashMap<String,ProxyDetails>(); proxyCache.put(cl, cacheForTheLoader); } - details = (ProxyDetails)cacheForTheLoader.get(key); + details = cacheForTheLoader.get(key); if (details != null) { - WeakReference reference = details.proxyClass; - thisClass = (Class)reference.get(); + Reference<Class<?>> reference = details.proxyClass; + thisClass = reference.get(); if (thisClass != null) { return; } @@ -553,11 +575,11 @@ public class ProxyFactory { } } - static byte[] getFilterSignature(Class clazz) { + static byte[] getFilterSignature(Class<?> clazz) { return (byte[])getField(clazz, FILTER_SIGNATURE_FIELD); } - private static Object getField(Class clazz, String fieldName) { + private static Object getField(Class<?> clazz, String fieldName) { try { Field f = clazz.getField(fieldName); f.setAccessible(true); @@ -625,12 +647,13 @@ public class ProxyFactory { * * @since 3.4 */ - public static ClassLoaderProvider classLoaderProvider - = new ClassLoaderProvider() { - public ClassLoader get(ProxyFactory pf) { + public static ClassLoaderProvider classLoaderProvider = + new ClassLoaderProvider() { + @Override + public ClassLoader get(ProxyFactory pf) { return pf.getClassLoader0(); } - }; + }; protected ClassLoader getClassLoader() { return classLoaderProvider.get(this); @@ -657,7 +680,7 @@ public class ProxyFactory { } protected ProtectionDomain getDomain() { - Class clazz; + Class<?> clazz; if (superClass != null && !superClass.getName().equals("java.lang.Object")) clazz = superClass; else if (interfaces != null && interfaces.length > 0) @@ -676,7 +699,7 @@ public class ProxyFactory { * @param mh the method handler for the proxy class. * @since 3.4 */ - public Object create(Class[] paramTypes, Object[] args, MethodHandler mh) + public Object create(Class<?>[] paramTypes, Object[] args, MethodHandler mh) throws NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { @@ -691,12 +714,12 @@ public class ProxyFactory { * @param paramTypes parameter types for a constructor. * @param args arguments passed to a constructor. */ - public Object create(Class[] paramTypes, Object[] args) + public Object create(Class<?>[] paramTypes, Object[] args) throws NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { - Class c = createClass(); - Constructor cons = c.getConstructor(paramTypes); + Class<?> c = createClass(); + Constructor<?> cons = c.getConstructor(paramTypes); return cons.newInstance(args); } @@ -710,6 +733,7 @@ public class ProxyFactory { * for each newly created proxy instance. * calling this method will automatically disable caching of classes created by the proxy factory. */ + @Deprecated public void setHandler(MethodHandler mi) { // if we were using the cache and the handler is non-null then we must stop caching if (factoryUseCache && mi != null) { @@ -746,6 +770,7 @@ public class ProxyFactory { private final String sep = "_$$_jvst" + Integer.toHexString(this.hashCode() & 0xfff) + "_"; private int counter = 0; + @Override public String get(String classname) { return classname + sep + Integer.toHexString(counter++); } @@ -784,12 +809,12 @@ public class ProxyFactory { FieldInfo finfo4 = new FieldInfo(pool, SERIAL_VERSION_UID_FIELD, SERIAL_VERSION_UID_TYPE); finfo4.setAccessFlags(AccessFlag.PUBLIC | AccessFlag.STATIC| AccessFlag.FINAL); cf.addField(finfo4); - + // HashMap allMethods = getMethods(superClass, interfaces); // int size = allMethods.size(); makeConstructors(classname, cf, pool, classname); - ArrayList forwarders = new ArrayList(); + List<Find2MethodsArgs> forwarders = new ArrayList<Find2MethodsArgs>(); int s = overrideMethods(cf, pool, classname, forwarders); addClassInitializer(cf, pool, classname, s, forwarders); addSetter(classname, cf, pool); @@ -825,7 +850,7 @@ public class ProxyFactory { if (Modifier.isFinal(superClass.getModifiers())) throw new RuntimeException(superName + " is final"); - + if (basename.startsWith("java.") || onlyPublicMethods) basename = "javassist.util.proxy." + basename.replace('.', '_'); } @@ -834,23 +859,20 @@ public class ProxyFactory { classname = makeProxyName(basename); } - private static Comparator sorter = new Comparator() { - - public int compare(Object o1, Object o2) { - Map.Entry e1 = (Map.Entry)o1; - Map.Entry e2 = (Map.Entry)o2; - String key1 = (String)e1.getKey(); - String key2 = (String)e2.getKey(); - return key1.compareTo(key2); - } - }; + private static Comparator<Map.Entry<String,Method>> sorter = + new Comparator<Map.Entry<String,Method>>() { + @Override + public int compare(Map.Entry<String,Method> e1, Map.Entry<String,Method> e2) { + return e1.getKey().compareTo(e2.getKey()); + } + }; private void makeSortedMethodList() { checkClassAndSuperName(); hasGetHandler = false; // getMethods() may set this to true. - HashMap allMethods = getMethods(superClass, interfaces); - signatureMethods = new ArrayList(allMethods.entrySet()); + Map<String,Method> allMethods = getMethods(superClass, interfaces); + signatureMethods = new ArrayList<Map.Entry<String,Method>>(allMethods.entrySet()); Collections.sort(signatureMethods, sorter); } @@ -863,8 +885,7 @@ public class ProxyFactory { signature = new byte[maxBytes]; for (int idx = 0; idx < l; idx++) { - Map.Entry e = (Map.Entry)signatureMethods.get(idx); - Method m = (Method)e.getValue(); + Method m = signatureMethods.get(idx).getValue(); int mod = m.getModifiers(); if (!Modifier.isFinal(mod) && !Modifier.isStatic(mod) && isVisible(mod, basename, m) && (filter == null || filter.isHandled(m))) { @@ -888,14 +909,12 @@ public class ProxyFactory { private boolean testBit(byte[] signature, int idx) { int byteIdx = idx >> 3; - if (byteIdx > signature.length) { + if (byteIdx > signature.length) return false; - } else { - int bitIdx = idx & 0x7; - int mask = 0x1 << bitIdx; - int sigByte = signature[byteIdx]; - return ((sigByte & mask) != 0); - } + int bitIdx = idx & 0x7; + int mask = 0x1 << bitIdx; + int sigByte = signature[byteIdx]; + return ((sigByte & mask) != 0); } private void setBit(byte[] signature, int idx) { @@ -908,7 +927,7 @@ public class ProxyFactory { } } - private static void setInterfaces(ClassFile cf, Class[] interfaces, Class proxyClass) { + private static void setInterfaces(ClassFile cf, Class<?>[] interfaces, Class<?> proxyClass) { String setterIntf = proxyClass.getName(); String[] list; if (interfaces == null || interfaces.length == 0) @@ -925,7 +944,7 @@ public class ProxyFactory { } private static void addClassInitializer(ClassFile cf, ConstPool cp, - String classname, int size, ArrayList forwarders) + String classname, int size, List<Find2MethodsArgs> forwarders) throws CannotCompileException { FieldInfo finfo = new FieldInfo(cp, HOLDER, HOLDER_TYPE); @@ -933,7 +952,7 @@ public class ProxyFactory { cf.addField(finfo); MethodInfo minfo = new MethodInfo(cp, "<clinit>", "()V"); minfo.setAccessFlags(AccessFlag.STATIC); - setThrows(minfo, cp, new Class[] { ClassNotFoundException.class }); + setThrows(minfo, cp, new Class<?>[] { ClassNotFoundException.class }); Bytecode code = new Bytecode(cp, 0, 2); code.addIconst(size * 2); @@ -949,12 +968,9 @@ public class ProxyFactory { final int varClass = 1; code.addAstore(varClass); - Iterator it = forwarders.iterator(); - while (it.hasNext()) { - Find2MethodsArgs args = (Find2MethodsArgs)it.next(); + for (Find2MethodsArgs args:forwarders) callFind2Methods(code, args.methodName, args.delegatorName, args.origIndex, args.descriptor, varClass, varArray); - } code.addAload(varArray); code.addPutstatic(classname, HOLDER, HOLDER_TYPE); @@ -1017,20 +1033,18 @@ public class ProxyFactory { cf.addMethod(minfo); } - private int overrideMethods(ClassFile cf, ConstPool cp, String className, ArrayList forwarders) + private int overrideMethods(ClassFile cf, ConstPool cp, String className, List<Find2MethodsArgs> forwarders) throws CannotCompileException { String prefix = makeUniqueName("_d", signatureMethods); - Iterator it = signatureMethods.iterator(); + Iterator<Map.Entry<String,Method>> it = signatureMethods.iterator(); int index = 0; while (it.hasNext()) { - Map.Entry e = (Map.Entry)it.next(); - String key = (String)e.getKey(); - Method meth = (Method)e.getValue(); - if (ClassFile.MAJOR_VERSION < ClassFile.JAVA_5 || !isBridge(meth)) + Map.Entry<String,Method> e = it.next(); + if (ClassFile.MAJOR_VERSION < ClassFile.JAVA_5 || !isBridge(e.getValue())) if (testBit(signature, index)) { - override(className, meth, prefix, index, - keyToDesc(key, meth), cf, cp, forwarders); + override(className, e.getValue(), prefix, index, + keyToDesc(e.getKey(), e.getValue()), cf, cp, forwarders); } index++; @@ -1044,10 +1058,11 @@ public class ProxyFactory { } private void override(String thisClassname, Method meth, String prefix, - int index, String desc, ClassFile cf, ConstPool cp, ArrayList forwarders) + int index, String desc, ClassFile cf, ConstPool cp, + List<Find2MethodsArgs> forwarders) throws CannotCompileException { - Class declClass = meth.getDeclaringClass(); + Class<?> declClass = meth.getDeclaringClass(); String delegatorName = prefix + index + meth.getName(); if (Modifier.isAbstract(meth.getModifiers())) delegatorName = null; @@ -1068,11 +1083,11 @@ public class ProxyFactory { private void makeConstructors(String thisClassName, ClassFile cf, ConstPool cp, String classname) throws CannotCompileException { - Constructor[] cons = SecurityActions.getDeclaredConstructors(superClass); + Constructor<?>[] cons = SecurityActions.getDeclaredConstructors(superClass); // legacy: if we are not caching then we need to initialise the default handler boolean doHandlerInit = !factoryUseCache; for (int i = 0; i < cons.length; i++) { - Constructor c = cons[i]; + Constructor<?> c = cons[i]; int mod = c.getModifiers(); if (!Modifier.isFinal(mod) && !Modifier.isPrivate(mod) && isVisible(mod, basename, c)) { @@ -1082,7 +1097,7 @@ public class ProxyFactory { } } - private static String makeUniqueName(String name, List sortedMethods) { + private static String makeUniqueName(String name, List<Map.Entry<String,Method>> sortedMethods) { if (makeUniqueName0(name, sortedMethods.iterator())) return name; @@ -1095,14 +1110,10 @@ public class ProxyFactory { throw new RuntimeException("cannot make a unique method name"); } - private static boolean makeUniqueName0(String name, Iterator it) { - while (it.hasNext()) { - Map.Entry e = (Map.Entry)it.next(); - String key = (String)e.getKey(); - if (key.startsWith(name)) + private static boolean makeUniqueName0(String name, Iterator<Map.Entry<String,Method>> it) { + while (it.hasNext()) + if (it.next().getKey().startsWith(name)) return false; - } - return true; } @@ -1121,8 +1132,7 @@ public class ProxyFactory { String q = getPackageName(meth.getDeclaringClass().getName()); if (p == null) return q == null; - else - return p.equals(q); + return p.equals(q); } } @@ -1130,15 +1140,14 @@ public class ProxyFactory { int i = name.lastIndexOf('.'); if (i < 0) return null; - else - return name.substring(0, i); + return name.substring(0, i); } /* getMethods() may set hasGetHandler to true. */ - private HashMap getMethods(Class superClass, Class[] interfaceTypes) { - HashMap hash = new HashMap(); - HashSet set = new HashSet(); + private Map<String,Method> getMethods(Class<?> superClass, Class<?>[] interfaceTypes) { + Map<String,Method> hash = new HashMap<String,Method>(); + Set<Class<?>> set = new HashSet<Class<?>>(); for (int i = 0; i < interfaceTypes.length; i++) getMethods(hash, interfaceTypes[i], set); @@ -1146,17 +1155,17 @@ public class ProxyFactory { return hash; } - private void getMethods(HashMap hash, Class clazz, Set visitedClasses) { + private void getMethods(Map<String,Method> hash, Class<?> clazz, Set<Class<?>> visitedClasses) { // This both speeds up scanning by avoiding duplicate interfaces and is needed to // ensure that superinterfaces are always scanned before subinterfaces. if (!visitedClasses.add(clazz)) return; - Class[] ifs = clazz.getInterfaces(); + Class<?>[] ifs = clazz.getInterfaces(); for (int i = 0; i < ifs.length; i++) getMethods(hash, ifs[i], visitedClasses); - Class parent = clazz.getSuperclass(); + Class<?> parent = clazz.getSuperclass(); if (parent != null) getMethods(hash, parent, visitedClasses); @@ -1174,8 +1183,8 @@ public class ProxyFactory { hasGetHandler = true; // JIRA JASSIST-85 - // put the method to the cache, retrieve previous definition (if any) - Method oldMethod = (Method)hash.put(key, m); + // put the method to the cache, retrieve previous definition (if any) + Method oldMethod = hash.put(key, m); // JIRA JASSIST-244 // ignore a bridge method with the same signature that the overridden one has. @@ -1211,8 +1220,8 @@ public class ProxyFactory { return key.substring(key.indexOf(':') + 1); } - private static MethodInfo makeConstructor(String thisClassName, Constructor cons, - ConstPool cp, Class superClass, boolean doHandlerInit) { + private static MethodInfo makeConstructor(String thisClassName, Constructor<?> cons, + ConstPool cp, Class<?> superClass, boolean doHandlerInit) { String desc = RuntimeSupport.makeDescriptor(cons.getParameterTypes(), Void.TYPE); MethodInfo minfo = new MethodInfo(cp, "<init>", desc); @@ -1253,7 +1262,7 @@ public class ProxyFactory { } private MethodInfo makeDelegator(Method meth, String desc, - ConstPool cp, Class declClass, String delegatorName) { + ConstPool cp, Class<?> declClass, String delegatorName) { MethodInfo delegator = new MethodInfo(cp, delegatorName, desc); delegator.setAccessFlags(Modifier.FINAL | Modifier.PUBLIC | (meth.getModifiers() & ~(Modifier.PRIVATE @@ -1265,7 +1274,7 @@ public class ProxyFactory { Bytecode code = new Bytecode(cp, 0, 0); code.addAload(0); int s = addLoadParameters(code, meth.getParameterTypes(), 1); - Class targetClass = invokespecialTarget(declClass); + Class<?> targetClass = invokespecialTarget(declClass); code.addInvokespecial(targetClass.isInterface(), cp.addClassInfo(targetClass.getName()), meth.getName(), desc); addReturn(code, meth.getReturnType()); @@ -1279,9 +1288,9 @@ public class ProxyFactory { * (or its interface). If S <: U <: T (S <: T reads "S extends T"), * the target type of invokespecial has to be not T but U. */ - private Class invokespecialTarget(Class declClass) { + private Class<?> invokespecialTarget(Class<?> declClass) { if (declClass.isInterface()) - for (Class i: interfaces) + for (Class<?> i: interfaces) if (declClass.isAssignableFrom(i)) return i; @@ -1293,8 +1302,8 @@ public class ProxyFactory { */ private static MethodInfo makeForwarder(String thisClassName, Method meth, String desc, ConstPool cp, - Class declClass, String delegatorName, int index, - ArrayList forwarders) { + Class<?> declClass, String delegatorName, int index, + List<Find2MethodsArgs> forwarders) { MethodInfo forwarder = new MethodInfo(cp, meth.getName(), desc); forwarder.setAccessFlags(Modifier.FINAL | (meth.getModifiers() & ~(Modifier.ABSTRACT @@ -1339,7 +1348,7 @@ public class ProxyFactory { code.addInvokeinterface(MethodHandler.class.getName(), "invoke", "(Ljava/lang/Object;Ljava/lang/reflect/Method;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;", 5); - Class retType = meth.getReturnType(); + Class<?> retType = meth.getReturnType(); addUnwrapper(code, retType); addReturn(code, retType); @@ -1361,12 +1370,12 @@ public class ProxyFactory { } private static void setThrows(MethodInfo minfo, ConstPool cp, Method orig) { - Class[] exceptions = orig.getExceptionTypes(); + Class<?>[] exceptions = orig.getExceptionTypes(); setThrows(minfo, cp, exceptions); } private static void setThrows(MethodInfo minfo, ConstPool cp, - Class[] exceptions) { + Class<?>[] exceptions) { if (exceptions.length == 0) return; @@ -1379,7 +1388,7 @@ public class ProxyFactory { minfo.setExceptionsAttribute(ea); } - private static int addLoadParameters(Bytecode code, Class[] params, + private static int addLoadParameters(Bytecode code, Class<?>[] params, int offset) { int stacksize = 0; int n = params.length; @@ -1389,7 +1398,7 @@ public class ProxyFactory { return stacksize; } - private static int addLoad(Bytecode code, int n, Class type) { + private static int addLoad(Bytecode code, int n, Class<?> type) { if (type.isPrimitive()) { if (type == Long.TYPE) { code.addLload(n); @@ -1410,7 +1419,7 @@ public class ProxyFactory { return 1; } - private static int addReturn(Bytecode code, Class type) { + private static int addReturn(Bytecode code, Class<?> type) { if (type.isPrimitive()) { if (type == Long.TYPE) { code.addOpcode(Opcode.LRETURN); @@ -1435,7 +1444,7 @@ public class ProxyFactory { return 1; } - private static void makeParameterList(Bytecode code, Class[] params) { + private static void makeParameterList(Bytecode code, Class<?>[] params) { int regno = 1; int n = params.length; code.addIconst(n); @@ -1443,7 +1452,7 @@ public class ProxyFactory { for (int i = 0; i < n; i++) { code.addOpcode(Opcode.DUP); code.addIconst(i); - Class type = params[i]; + Class<?> type = params[i]; if (type.isPrimitive()) regno = makeWrapper(code, type, regno); else { @@ -1455,7 +1464,7 @@ public class ProxyFactory { } } - private static int makeWrapper(Bytecode code, Class type, int regno) { + private static int makeWrapper(Bytecode code, Class<?> type, int regno) { int index = FactoryHelper.typeIndex(type); String wrapper = FactoryHelper.wrapperTypes[index]; code.addNew(wrapper); @@ -1466,7 +1475,7 @@ public class ProxyFactory { return regno + FactoryHelper.dataSize[index]; } - private static void addUnwrapper(Bytecode code, Class type) { + private static void addUnwrapper(Bytecode code, Class<?> type) { if (type.isPrimitive()) { if (type == Void.TYPE) code.addOpcode(Opcode.POP); diff --git a/src/main/javassist/util/proxy/ProxyObject.java b/src/main/javassist/util/proxy/ProxyObject.java index f04ae9a4..a5a39e26 100644 --- a/src/main/javassist/util/proxy/ProxyObject.java +++ b/src/main/javassist/util/proxy/ProxyObject.java @@ -31,6 +31,7 @@ public interface ProxyObject extends Proxy { * Sets a handler. It can be used for changing handlers * during runtime. */ + @Override void setHandler(MethodHandler mi); /** diff --git a/src/main/javassist/util/proxy/ProxyObjectInputStream.java b/src/main/javassist/util/proxy/ProxyObjectInputStream.java index 25ae4d20..2992cc95 100644 --- a/src/main/javassist/util/proxy/ProxyObjectInputStream.java +++ b/src/main/javassist/util/proxy/ProxyObjectInputStream.java @@ -63,13 +63,14 @@ public class ProxyObjectInputStream extends ObjectInputStream } } + @Override protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { boolean isProxy = readBoolean(); if (isProxy) { String name = (String)readObject(); - Class superClass = loader.loadClass(name); + Class<?> superClass = loader.loadClass(name); int length = readInt(); - Class[] interfaces = new Class[length]; + Class<?>[] interfaces = new Class[length]; for (int i = 0; i < length; i++) { name = (String)readObject(); interfaces[i] = loader.loadClass(name); @@ -84,11 +85,10 @@ public class ProxyObjectInputStream extends ObjectInputStream factory.setUseWriteReplace(false); factory.setSuperclass(superClass); factory.setInterfaces(interfaces); - Class proxyClass = factory.createClass(signature); + Class<?> proxyClass = factory.createClass(signature); return ObjectStreamClass.lookup(proxyClass); - } else { - return super.readClassDescriptor(); } + return super.readClassDescriptor(); } /** diff --git a/src/main/javassist/util/proxy/ProxyObjectOutputStream.java b/src/main/javassist/util/proxy/ProxyObjectOutputStream.java index 31c3861b..87351685 100644 --- a/src/main/javassist/util/proxy/ProxyObjectOutputStream.java +++ b/src/main/javassist/util/proxy/ProxyObjectOutputStream.java @@ -44,19 +44,20 @@ public class ProxyObjectOutputStream extends ObjectOutputStream super(out); } + @Override protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException { - Class cl = desc.forClass(); + Class<?> cl = desc.forClass(); if (ProxyFactory.isProxyClass(cl)) { writeBoolean(true); - Class superClass = cl.getSuperclass(); - Class[] interfaces = cl.getInterfaces(); + Class<?> superClass = cl.getSuperclass(); + Class<?>[] interfaces = cl.getInterfaces(); byte[] signature = ProxyFactory.getFilterSignature(cl); String name = superClass.getName(); writeObject(name); // we don't write the marker interface ProxyObject writeInt(interfaces.length - 1); for (int i = 0; i < interfaces.length; i++) { - Class interfaze = interfaces[i]; + Class<?> interfaze = interfaces[i]; if (interfaze != ProxyObject.class && interfaze != Proxy.class) { name = interfaces[i].getName(); writeObject(name); diff --git a/src/main/javassist/util/proxy/RuntimeSupport.java b/src/main/javassist/util/proxy/RuntimeSupport.java index 371d553d..0bd0cce9 100644 --- a/src/main/javassist/util/proxy/RuntimeSupport.java +++ b/src/main/javassist/util/proxy/RuntimeSupport.java @@ -16,8 +16,8 @@ package javassist.util.proxy; -import java.lang.reflect.Method; import java.io.Serializable; +import java.lang.reflect.Method; /** * Runtime support routines that the classes generated by ProxyFactory use. @@ -31,6 +31,10 @@ public class RuntimeSupport { public static MethodHandler default_interceptor = new DefaultMethodHandler(); static class DefaultMethodHandler implements MethodHandler, Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + + @Override public Object invoke(Object self, Method m, Method proceed, Object[] args) throws Exception @@ -46,7 +50,7 @@ public class RuntimeSupport { * @throws RuntimeException if the methods are not found. * @see javassist.util.proxy.ProxyFactory */ - public static void find2Methods(Class clazz, String superMethod, + public static void find2Methods(Class<?> clazz, String superMethod, String thisMethod, int index, String desc, java.lang.reflect.Method[] methods) { @@ -65,6 +69,7 @@ public class RuntimeSupport { * @see javassist.util.proxy.ProxyFactory * @deprecated replaced by {@link #find2Methods(Class, String, String, int, String, Method[])} */ + @Deprecated public static void find2Methods(Object self, String superMethod, String thisMethod, int index, String desc, java.lang.reflect.Method[] methods) @@ -83,6 +88,7 @@ public class RuntimeSupport { * @throws RuntimeException if the method is not found. * @deprecated replaced by {@link #findMethod(Class, String, String)} */ + @Deprecated public static Method findMethod(Object self, String name, String desc) { Method m = findMethod2(self.getClass(), name, desc); if (m == null) @@ -97,7 +103,7 @@ public class RuntimeSupport { * * @throws RuntimeException if the method is not found. */ - public static Method findMethod(Class clazz, String name, String desc) { + public static Method findMethod(Class<?> clazz, String name, String desc) { Method m = findMethod2(clazz, name, desc); if (m == null) error(clazz, name, desc); @@ -113,7 +119,7 @@ public class RuntimeSupport { */ public static Method findSuperMethod(Object self, String name, String desc) { // for JBoss Seam. See JASSIST-183. - Class clazz = self.getClass(); + Class<?> clazz = self.getClass(); return findSuperClassMethod(clazz, name, desc); } @@ -123,7 +129,7 @@ public class RuntimeSupport { * * @throws RuntimeException if the method is not found. */ - public static Method findSuperClassMethod(Class clazz, String name, String desc) { + public static Method findSuperClassMethod(Class<?> clazz, String name, String desc) { Method m = findSuperMethod2(clazz.getSuperclass(), name, desc); if (m == null) m = searchInterfaces(clazz, name, desc); @@ -134,17 +140,17 @@ public class RuntimeSupport { return m; } - private static void error(Class clazz, String name, String desc) { + private static void error(Class<?> clazz, String name, String desc) { throw new RuntimeException("not found " + name + ":" + desc + " in " + clazz.getName()); } - private static Method findSuperMethod2(Class clazz, String name, String desc) { + private static Method findSuperMethod2(Class<?> clazz, String name, String desc) { Method m = findMethod2(clazz, name, desc); if (m != null) return m; - Class superClass = clazz.getSuperclass(); + Class<?> superClass = clazz.getSuperclass(); if (superClass != null) { m = findSuperMethod2(superClass, name, desc); if (m != null) @@ -154,9 +160,9 @@ public class RuntimeSupport { return searchInterfaces(clazz, name, desc); } - private static Method searchInterfaces(Class clazz, String name, String desc) { + private static Method searchInterfaces(Class<?> clazz, String name, String desc) { Method m = null; - Class[] interfaces = clazz.getInterfaces(); + Class<?>[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { m = findSuperMethod2(interfaces[i], name, desc); if (m != null) @@ -166,7 +172,7 @@ public class RuntimeSupport { return m; } - private static Method findMethod2(Class clazz, String name, String desc) { + private static Method findMethod2(Class<?> clazz, String name, String desc) { Method[] methods = SecurityActions.getDeclaredMethods(clazz); int n = methods.length; for (int i = 0; i < n; i++) @@ -181,7 +187,7 @@ public class RuntimeSupport { * Makes a descriptor for a given method. */ public static String makeDescriptor(Method m) { - Class[] params = m.getParameterTypes(); + Class<?>[] params = m.getParameterTypes(); return makeDescriptor(params, m.getReturnType()); } @@ -191,7 +197,7 @@ public class RuntimeSupport { * @param params parameter types. * @param retType return type. */ - public static String makeDescriptor(Class[] params, Class retType) { + public static String makeDescriptor(Class<?>[] params, Class<?> retType) { StringBuffer sbuf = new StringBuffer(); sbuf.append('('); for (int i = 0; i < params.length; i++) @@ -210,13 +216,13 @@ public class RuntimeSupport { * @param params the descriptor of parameter types. * @param retType return type. */ - public static String makeDescriptor(String params, Class retType) { + public static String makeDescriptor(String params, Class<?> retType) { StringBuffer sbuf = new StringBuffer(params); makeDesc(sbuf, retType); return sbuf.toString(); } - private static void makeDesc(StringBuffer sbuf, Class type) { + private static void makeDesc(StringBuffer sbuf, Class<?> type) { if (type.isArray()) { sbuf.append('['); makeDesc(sbuf, type.getComponentType()); @@ -258,7 +264,7 @@ public class RuntimeSupport { public static SerializedProxy makeSerializedProxy(Object proxy) throws java.io.InvalidClassException { - Class clazz = proxy.getClass(); + Class<?> clazz = proxy.getClass(); MethodHandler methodHandler = null; if (proxy instanceof ProxyObject) diff --git a/src/main/javassist/util/proxy/SerializedProxy.java b/src/main/javassist/util/proxy/SerializedProxy.java index a0485da0..1417a04b 100644 --- a/src/main/javassist/util/proxy/SerializedProxy.java +++ b/src/main/javassist/util/proxy/SerializedProxy.java @@ -16,13 +16,14 @@ package javassist.util.proxy; +import java.io.InvalidClassException; +import java.io.InvalidObjectException; +import java.io.ObjectStreamException; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; -import java.io.ObjectStreamException; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; -import java.security.ProtectionDomain; /** * A proxy object is converted into an instance of this class @@ -31,16 +32,18 @@ import java.security.ProtectionDomain; * @see RuntimeSupport#makeSerializedProxy(Object) */ class SerializedProxy implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private String superClass; private String[] interfaces; private byte[] filterSignature; private MethodHandler handler; - SerializedProxy(Class proxy, byte[] sig, MethodHandler h) { + SerializedProxy(Class<?> proxy, byte[] sig, MethodHandler h) { filterSignature = sig; handler = h; superClass = proxy.getSuperclass().getName(); - Class[] infs = proxy.getInterfaces(); + Class<?>[] infs = proxy.getInterfaces(); int n = infs.length; interfaces = new String[n - 1]; String setterInf = ProxyObject.class.getName(); @@ -59,10 +62,11 @@ class SerializedProxy implements Serializable { * @return loaded class * @throws ClassNotFoundException for any error */ - protected Class loadClass(final String className) throws ClassNotFoundException { + protected Class<?> loadClass(final String className) throws ClassNotFoundException { try { - return (Class)AccessController.doPrivileged(new PrivilegedExceptionAction(){ - public Object run() throws Exception{ + return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>(){ + @Override + public Class<?> run() throws Exception{ ClassLoader cl = Thread.currentThread().getContextClassLoader(); return Class.forName(className, true, cl); } @@ -76,7 +80,7 @@ class SerializedProxy implements Serializable { Object readResolve() throws ObjectStreamException { try { int n = interfaces.length; - Class[] infs = new Class[n]; + Class<?>[] infs = new Class[n]; for (int i = 0; i < n; i++) infs[i] = loadClass(interfaces[i]); @@ -88,19 +92,19 @@ class SerializedProxy implements Serializable { return proxy; } catch (NoSuchMethodException e) { - throw new java.io.InvalidClassException(e.getMessage()); + throw new InvalidClassException(e.getMessage()); } catch (InvocationTargetException e) { - throw new java.io.InvalidClassException(e.getMessage()); + throw new InvalidClassException(e.getMessage()); } catch (ClassNotFoundException e) { - throw new java.io.InvalidClassException(e.getMessage()); + throw new InvalidClassException(e.getMessage()); } catch (InstantiationException e2) { - throw new java.io.InvalidObjectException(e2.getMessage()); + throw new InvalidObjectException(e2.getMessage()); } catch (IllegalAccessException e3) { - throw new java.io.InvalidClassException(e3.getMessage()); + throw new InvalidClassException(e3.getMessage()); } } } diff --git a/src/test/Jassist150.java b/src/test/Jassist150.java index d3945069..2d57da06 100644 --- a/src/test/Jassist150.java +++ b/src/test/Jassist150.java @@ -6,6 +6,7 @@ import javassist.NotFoundException; import javassist.expr.ExprEditor; import javassist.expr.MethodCall; +@SuppressWarnings("unused") public class Jassist150 { public static final String BASE_PATH = "./"; public static final String JAVASSIST_JAR = BASE_PATH + "javassist.jar"; diff --git a/src/test/Test.java b/src/test/Test.java index b01a6211..9907406d 100644 --- a/src/test/Test.java +++ b/src/test/Test.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.List; import javassist.*; +@SuppressWarnings("unused") class InvalidStackMapFrame { public void bytecodeVerifyError1() { diff --git a/src/test/VisibleTop.java b/src/test/VisibleTop.java index 6430bd70..0bb6161f 100644 --- a/src/test/VisibleTop.java +++ b/src/test/VisibleTop.java @@ -1,3 +1,4 @@ +@SuppressWarnings("unused") public class VisibleTop { public int pub; protected int pro; diff --git a/src/test/VisibleTop2.java b/src/test/VisibleTop2.java index 93fed9da..a09a1396 100644 --- a/src/test/VisibleTop2.java +++ b/src/test/VisibleTop2.java @@ -1,3 +1,4 @@ +@SuppressWarnings("unused") public class VisibleTop2 { public int pub; protected int pro; diff --git a/src/test/javassist/Bench.java b/src/test/javassist/Bench.java index 723fa198..b7b8b27e 100644 --- a/src/test/javassist/Bench.java +++ b/src/test/javassist/Bench.java @@ -153,11 +153,6 @@ public class Bench extends JvstTestRoot { System.out.println("println: " + (t5 * 10) + " usec"); } - public static void main(String[] args) { - // junit.textui.TestRunner.run(suite()); - junit.swingui.TestRunner.main(new String[] { "javassist.Bench" }); - } - public static Test suite() { TestSuite suite = new TestSuite("Benchmark Tests"); suite.addTestSuite(Bench.class); diff --git a/src/test/javassist/ClassPoolBench.java b/src/test/javassist/ClassPoolBench.java index d3cb6b2d..bf71051c 100644 --- a/src/test/javassist/ClassPoolBench.java +++ b/src/test/javassist/ClassPoolBench.java @@ -24,6 +24,7 @@ public class ClassPoolBench { cc.detach();
}
+ @SuppressWarnings("rawtypes")
public static void accessAll(String filename) throws Exception {
ZipFile zip = new ZipFile(filename);
Enumeration files = zip.entries();
diff --git a/src/test/javassist/JvstTest.java b/src/test/javassist/JvstTest.java index 11cdbe96..436dc6de 100644 --- a/src/test/javassist/JvstTest.java +++ b/src/test/javassist/JvstTest.java @@ -8,6 +8,7 @@ import javassist.bytecode.*; import javassist.expr.*; import javassist.runtime.*; +@SuppressWarnings({"rawtypes","unused", "resource"}) public class JvstTest extends JvstTestRoot { public static boolean java9; diff --git a/src/test/javassist/JvstTest2.java b/src/test/javassist/JvstTest2.java index ec314e12..117560c0 100644 --- a/src/test/javassist/JvstTest2.java +++ b/src/test/javassist/JvstTest2.java @@ -2,10 +2,16 @@ package javassist; import java.io.*; import java.net.URL; + +import org.junit.FixMethodOrder; +import org.junit.runners.MethodSorters; + import java.lang.reflect.Method; import javassist.expr.*; +@SuppressWarnings({"rawtypes","unused"}) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) public class JvstTest2 extends JvstTestRoot { public JvstTest2(String name) { super(name); diff --git a/src/test/javassist/JvstTest3.java b/src/test/javassist/JvstTest3.java index 056df5c2..47131a93 100644 --- a/src/test/javassist/JvstTest3.java +++ b/src/test/javassist/JvstTest3.java @@ -5,6 +5,7 @@ import javassist.bytecode.annotation.*; import javassist.expr.*; import test3.*; +@SuppressWarnings({"rawtypes","unchecked","unused"}) public class JvstTest3 extends JvstTestRoot { public JvstTest3(String name) { super(name); diff --git a/src/test/javassist/JvstTest4.java b/src/test/javassist/JvstTest4.java index 467caf2b..187abb3d 100644 --- a/src/test/javassist/JvstTest4.java +++ b/src/test/javassist/JvstTest4.java @@ -6,10 +6,15 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.HashSet; +import org.junit.FixMethodOrder; +import org.junit.runners.MethodSorters; + import javassist.bytecode.*; import javassist.bytecode.annotation.Annotation; import javassist.expr.*; +@SuppressWarnings({"rawtypes","unchecked","unused"}) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) public class JvstTest4 extends JvstTestRoot { public JvstTest4(String name) { super(name); @@ -599,6 +604,7 @@ public class JvstTest4 extends JvstTestRoot { }); } + @SuppressWarnings("deprecation") public void testMakePackage() throws Exception { if (ClassFile.MAJOR_VERSION >= ClassFile.JAVA_9) { ClassPool pool = ClassPool.getDefault(); @@ -610,6 +616,7 @@ public class JvstTest4 extends JvstTestRoot { } } + @SuppressWarnings("deprecation") public void testPackage() throws Throwable { // JASSIST-147 String packageName = "test4.pack"; ClassPool pool = ClassPool.getDefault(); @@ -628,7 +635,7 @@ public class JvstTest4 extends JvstTestRoot { assertEquals(packageName, obj.getClass().getPackage().getName()); } - public static final String BASE_PATH = "../"; + public static final String BASE_PATH = "../../"; public static final String JAVASSIST_JAR = BASE_PATH + "javassist.jar"; public static final String CLASSES_FOLDER = BASE_PATH + "build/classes"; public static final String TEST_CLASSES_FOLDER = BASE_PATH + "build/test-classes"; diff --git a/src/test/javassist/JvstTest5.java b/src/test/javassist/JvstTest5.java index 76d0c1a2..578abfb2 100644 --- a/src/test/javassist/JvstTest5.java +++ b/src/test/javassist/JvstTest5.java @@ -12,6 +12,7 @@ import javassist.bytecode.InnerClassesAttribute; import javassist.expr.ExprEditor; import javassist.expr.MethodCall; +@SuppressWarnings({"rawtypes","unchecked","unused"}) public class JvstTest5 extends JvstTestRoot { public JvstTest5(String name) { super(name); diff --git a/src/test/javassist/JvstTestRoot.java b/src/test/javassist/JvstTestRoot.java index 118e8511..69f4a6ae 100644 --- a/src/test/javassist/JvstTestRoot.java +++ b/src/test/javassist/JvstTestRoot.java @@ -5,10 +5,10 @@ import java.lang.reflect.Method; public class JvstTestRoot extends TestCase { // the directory where all compiled class files are found. - public static final String PATH = "../target/test-classes/"; + public static final String PATH = "../../target/test-classes/"; // the directory where javassist.jar is found. - public static final String JAR_PATH = "../"; + public static final String JAR_PATH = "../../"; ClassPool sloader, dloader; Loader cloader; diff --git a/src/test/javassist/LoaderTestByRandall.java b/src/test/javassist/LoaderTestByRandall.java index 1b8825f6..04e05cd8 100644 --- a/src/test/javassist/LoaderTestByRandall.java +++ b/src/test/javassist/LoaderTestByRandall.java @@ -11,6 +11,7 @@ import junit.framework.TestCase; /**
* @author brandall
*/
+@SuppressWarnings({"rawtypes","unused"})
public class LoaderTestByRandall extends TestCase {
ClassPool cp;
diff --git a/src/test/javassist/SetterTest.java b/src/test/javassist/SetterTest.java index a989d39a..44eec140 100644 --- a/src/test/javassist/SetterTest.java +++ b/src/test/javassist/SetterTest.java @@ -3,6 +3,7 @@ import java.lang.reflect.Method; import junit.framework.TestCase;
+@SuppressWarnings({"rawtypes","unchecked"})
public class SetterTest extends TestCase {
ClassPool pool;
diff --git a/src/test/javassist/bytecode/BytecodeTest.java b/src/test/javassist/bytecode/BytecodeTest.java index a859f248..5ddf5d5b 100644 --- a/src/test/javassist/bytecode/BytecodeTest.java +++ b/src/test/javassist/bytecode/BytecodeTest.java @@ -7,6 +7,7 @@ import javassist.*; import javassist.bytecode.annotation.*; import javassist.bytecode.SignatureAttribute.*; +@SuppressWarnings("unused") public class BytecodeTest extends TestCase { public static final String PATH = JvstTest.PATH; private ClassPool loader, dloader; @@ -826,12 +827,6 @@ public class BytecodeTest extends TestCase { assertEquals("(I)V", cPool2.getUtf8Info(cPool2.getMethodTypeInfo(mtIndex))); } - public static void main(String[] args) { - // junit.textui.TestRunner.run(suite()); - junit.awtui.TestRunner.main(new String[] { - "javassist.bytecode.BytecodeTest" }); - } - public static Test suite() { TestSuite suite = new TestSuite("Bytecode Tests"); suite.addTestSuite(BytecodeTest.class); diff --git a/src/test/javassist/bytecode/CodeAnalyzerTest.java b/src/test/javassist/bytecode/CodeAnalyzerTest.java index 4f115687..b6b33189 100644 --- a/src/test/javassist/bytecode/CodeAnalyzerTest.java +++ b/src/test/javassist/bytecode/CodeAnalyzerTest.java @@ -5,6 +5,7 @@ import java.util.Enumeration; import java.util.List;
import java.io.*;
+@SuppressWarnings({"rawtypes","resource"})
public class CodeAnalyzerTest {
public static void main(String[] args) throws Exception {
ZipFile zfile = new ZipFile(args[0]);
diff --git a/src/test/javassist/bytecode/InsertGap0.java b/src/test/javassist/bytecode/InsertGap0.java index 6a034141..824b9305 100644 --- a/src/test/javassist/bytecode/InsertGap0.java +++ b/src/test/javassist/bytecode/InsertGap0.java @@ -2,6 +2,7 @@ package javassist.bytecode; import javassist.*; +@SuppressWarnings("unused") final class Gap0Example { public static int counter = 1; @@ -70,6 +71,7 @@ final class Gap0Example { } } +@SuppressWarnings("unused") final class Gap0Example2 { public static int counter = 1; @@ -155,6 +157,7 @@ final class Gap0Example2 { } } +@SuppressWarnings({"rawtypes","unchecked","unused"}) public final class InsertGap0 extends JvstTestRoot { public InsertGap0(String name) { super(name); diff --git a/src/test/javassist/bytecode/StackMapTest.java b/src/test/javassist/bytecode/StackMapTest.java index 77d827be..153f75ac 100644 --- a/src/test/javassist/bytecode/StackMapTest.java +++ b/src/test/javassist/bytecode/StackMapTest.java @@ -21,6 +21,7 @@ import javassist.bytecode.stackmap.MapMaker; import javassist.bytecode.stackmap.TypeData; import junit.framework.TestCase; +@SuppressWarnings({"rawtypes","unused"}) public class StackMapTest extends TestCase { public static final String PATH = JvstTest.PATH; private ClassPool loader, dloader; diff --git a/src/test/javassist/compiler/CompTest.java b/src/test/javassist/compiler/CompTest.java index 6a1d5424..4154935f 100644 --- a/src/test/javassist/compiler/CompTest.java +++ b/src/test/javassist/compiler/CompTest.java @@ -113,12 +113,6 @@ public class CompTest extends TestCase { assertEquals("(int,char[],String)", s); } - public static void main(String[] args) { - // junit.textui.TestRunner.run(suite()); - junit.awtui.TestRunner.main(new String[] { - "javassist.compiler.CompTest" }); - } - public static Test suite() { TestSuite suite = new TestSuite("Compiler Tests"); suite.addTestSuite(CompTest.class); @@ -131,6 +125,7 @@ class Print{ public static int k; } +@SuppressWarnings({"rawtypes","unchecked"}) class HelloAspect{ List list; diff --git a/src/test/javassist/proxyfactory/MyCls.java b/src/test/javassist/proxyfactory/MyCls.java index 43fcb8dd..c4c5f35e 100644 --- a/src/test/javassist/proxyfactory/MyCls.java +++ b/src/test/javassist/proxyfactory/MyCls.java @@ -7,6 +7,8 @@ import java.io.Serializable; */ public class MyCls implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private int i,j; public int getI() { diff --git a/src/test/javassist/proxyfactory/ProxyFactoryTest.java b/src/test/javassist/proxyfactory/ProxyFactoryTest.java index 2b41af7a..3189b568 100644 --- a/src/test/javassist/proxyfactory/ProxyFactoryTest.java +++ b/src/test/javassist/proxyfactory/ProxyFactoryTest.java @@ -11,6 +11,7 @@ import java.lang.reflect.Method; /** * <a href="mailto:struberg@yahoo.de">Mark Struberg</a> */ +@SuppressWarnings({"rawtypes","unchecked","unused"}) public class ProxyFactoryTest extends TestCase { public void testMethodHandlers() throws Exception { ProxyFactory fact = new ProxyFactory(); @@ -59,6 +60,8 @@ public class ProxyFactoryTest extends TestCase { public static class MyMethodHandler implements MethodHandler, Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; private int x; public int getX() { diff --git a/src/test/javassist/proxyfactory/Tester.java b/src/test/javassist/proxyfactory/Tester.java index 601076da..874fba1e 100644 --- a/src/test/javassist/proxyfactory/Tester.java +++ b/src/test/javassist/proxyfactory/Tester.java @@ -8,12 +8,18 @@ import java.io.ByteArrayOutputStream; import java.lang.reflect.Method; class Hand implements java.io.Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; public int setHandler(int i) { return i; } int getHandler() { return 3; } } +@SuppressWarnings({"rawtypes","unchecked","resource"}) public class Tester extends TestCase { static class MHandler implements MethodHandler, java.io.Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public Object invoke(Object self, Method m, Method proceed, Object[] args) throws Throwable { System.out.println("Name: " + m.getName()); diff --git a/src/test/javassist/tools/reflect/Person.java b/src/test/javassist/tools/reflect/Person.java index 739d5948..c9e061c6 100644 --- a/src/test/javassist/tools/reflect/Person.java +++ b/src/test/javassist/tools/reflect/Person.java @@ -3,7 +3,7 @@ package javassist.tools.reflect; import java.lang.reflect.Method;
import java.util.Arrays;
-import junit.framework.Assert;
+import org.junit.Assert;
/**
* Work with ClassMetaobjectTest.java
diff --git a/src/test/javassist/tools/reflect/SubClass.java b/src/test/javassist/tools/reflect/SubClass.java index dd818316..cf42f77d 100644 --- a/src/test/javassist/tools/reflect/SubClass.java +++ b/src/test/javassist/tools/reflect/SubClass.java @@ -1,6 +1,6 @@ package javassist.tools.reflect;
-import junit.framework.*;
+import org.junit.Assert;
public class SubClass extends SuperClass {
public String f() { return "f2"; } // override
diff --git a/src/test/test/javassist/bytecode/analysis/AnalyzerTest.java b/src/test/test/javassist/bytecode/analysis/AnalyzerTest.java index 0c5a77e6..b76ff0e7 100644 --- a/src/test/test/javassist/bytecode/analysis/AnalyzerTest.java +++ b/src/test/test/javassist/bytecode/analysis/AnalyzerTest.java @@ -319,13 +319,17 @@ public class AnalyzerTest extends TestCase { public static class A {}; - public static class B1 extends A implements Serializable {}; - public static class B2 extends A implements Serializable {}; - public static class A2 implements Serializable, Cloneable {}; - public static class A3 implements Serializable, Cloneable {}; - + public static class B1 extends A implements Serializable { + private static final long serialVersionUID = 1L;}; + public static class B2 extends A implements Serializable { + private static final long serialVersionUID = 1L;}; + public static class A2 implements Serializable, Cloneable { + private static final long serialVersionUID = 1L;}; + public static class A3 implements Serializable, Cloneable { + private static final long serialVersionUID = 1L;}; public static class B3 extends A {}; - public static class C31 extends B3 implements Serializable {}; + public static class C31 extends B3 implements Serializable { + private static final long serialVersionUID = 1L;}; public void dummy(Serializable s) {} @@ -359,6 +363,7 @@ public class AnalyzerTest extends TestCase { } + @SuppressWarnings("rawtypes") public void reusedLocalMerge() { ArrayList list = new ArrayList(); try { diff --git a/src/test/test/javassist/convert/ArrayAccessReplaceTest.java b/src/test/test/javassist/convert/ArrayAccessReplaceTest.java index 58ea8357..d81f220d 100644 --- a/src/test/test/javassist/convert/ArrayAccessReplaceTest.java +++ b/src/test/test/javassist/convert/ArrayAccessReplaceTest.java @@ -147,6 +147,7 @@ public class ArrayAccessReplaceTest extends TestCase { } } + @SuppressWarnings({"rawtypes","unchecked"}) public static class Echo { public static Map byteMap = new HashMap(); public static Map charMap = new HashMap(); diff --git a/src/test/test/javassist/proxy/JBPAPP9257Test.java b/src/test/test/javassist/proxy/JBPAPP9257Test.java index 3549f2df..773e18b0 100644 --- a/src/test/test/javassist/proxy/JBPAPP9257Test.java +++ b/src/test/test/javassist/proxy/JBPAPP9257Test.java @@ -8,6 +8,7 @@ import javassist.util.proxy.ProxyObject; import javassist.util.proxy.Proxy; import junit.framework.TestCase; +@SuppressWarnings({"rawtypes","unchecked"}) public class JBPAPP9257Test extends TestCase { public void testGetHandler() throws Exception { ProxyFactory f = new ProxyFactory(); diff --git a/src/test/test/javassist/proxy/ProxyCacheGCTest.java b/src/test/test/javassist/proxy/ProxyCacheGCTest.java index e4331bbd..97b7281d 100644 --- a/src/test/test/javassist/proxy/ProxyCacheGCTest.java +++ b/src/test/test/javassist/proxy/ProxyCacheGCTest.java @@ -11,6 +11,7 @@ import junit.framework.TestCase; * test which checks that proxy classes are not retained after their classloader is released. * this is a before and after test which validates JASSIST-104 */ +@SuppressWarnings({"rawtypes","unchecked"}) public class ProxyCacheGCTest extends TestCase { /** diff --git a/src/test/test/javassist/proxy/ProxyFactoryCompatibilityTest.java b/src/test/test/javassist/proxy/ProxyFactoryCompatibilityTest.java index 634e6c14..861abb72 100644 --- a/src/test/test/javassist/proxy/ProxyFactoryCompatibilityTest.java +++ b/src/test/test/javassist/proxy/ProxyFactoryCompatibilityTest.java @@ -16,6 +16,7 @@ import java.lang.reflect.Method; * automatically disabled if this legacy api is used. it also exercises the new style * api, ensuring that caching works correctly with this model. */ +@SuppressWarnings({"rawtypes","unchecked","unused"}) public class ProxyFactoryCompatibilityTest extends TestCase { private ClassPool basePool; diff --git a/src/test/test/javassist/proxy/ProxySerializationTest.java b/src/test/test/javassist/proxy/ProxySerializationTest.java index 28125de0..39d94f7e 100644 --- a/src/test/test/javassist/proxy/ProxySerializationTest.java +++ b/src/test/test/javassist/proxy/ProxySerializationTest.java @@ -13,6 +13,7 @@ import java.lang.reflect.Method; * {@link javassist.util.proxy.ProxyObjectOutputStream} and @link javassist.util.proxy.ProxyObjectInputStream} * reuses classes located in the proxy cache. This tests the fixes provided for JASSIST-42 and JASSIST-97. */ +@SuppressWarnings({"rawtypes","unchecked","unused","resource"}) public class ProxySerializationTest extends TestCase { public void testSerialization() @@ -80,6 +81,9 @@ public class ProxySerializationTest extends TestCase public static class TestFilter implements MethodFilter, Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public boolean isHandled(Method m) { if (m.getName().equals("getName")) { return true; @@ -105,6 +109,9 @@ public class ProxySerializationTest extends TestCase public static class TestHandler implements MethodHandler, Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { return proceed.invoke(self, args); @@ -127,6 +134,8 @@ public class ProxySerializationTest extends TestCase public static class TestClass implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; public String name; public TestClass() diff --git a/src/test/test/javassist/proxy/ProxySimpleTest.java b/src/test/test/javassist/proxy/ProxySimpleTest.java index bbae9d8d..212c15fa 100644 --- a/src/test/test/javassist/proxy/ProxySimpleTest.java +++ b/src/test/test/javassist/proxy/ProxySimpleTest.java @@ -14,6 +14,7 @@ import javassist.util.proxy.MethodHandler; import javassist.util.proxy.Proxy; import javassist.util.proxy.ProxyFactory; +@SuppressWarnings({"rawtypes","unchecked"}) public class ProxySimpleTest extends TestCase { String testResult; @@ -84,6 +85,9 @@ public class ProxySimpleTest extends TestCase { } public static class ReadWriteData implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public int foo() { return 4; } } @@ -102,10 +106,16 @@ public class ProxySimpleTest extends TestCase { } public static class WriteReplace implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public Object writeReplace() { return this; } } public static class WriteReplace2 implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public Object writeReplace(int i) { return Integer.valueOf(i); } } diff --git a/src/test/test/javassist/tools/DummyClass.java b/src/test/test/javassist/tools/DummyClass.java index 020aa55d..ab9400f6 100644 --- a/src/test/test/javassist/tools/DummyClass.java +++ b/src/test/test/javassist/tools/DummyClass.java @@ -2,6 +2,7 @@ package test.javassist.tools; public class DummyClass { + @SuppressWarnings("unused") private String dummyString = "dummyStringValue"; public void dummyMethod(){} diff --git a/src/test/test1/FieldMod.java b/src/test/test1/FieldMod.java index 0023d2e3..2d68b335 100644 --- a/src/test/test1/FieldMod.java +++ b/src/test/test1/FieldMod.java @@ -1,6 +1,7 @@ package test1;
public class FieldMod {
+ @SuppressWarnings("unused") private String text;
public int i;
}
diff --git a/src/test/test1/GetThrowables.java b/src/test/test1/GetThrowables.java index 19e9a8a5..11ff3e05 100644 --- a/src/test/test1/GetThrowables.java +++ b/src/test/test1/GetThrowables.java @@ -1,9 +1,15 @@ package test1; class GetThrow1 extends Exception { + + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; } class GetThrow2 extends Exception { + + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; } public class GetThrowables { diff --git a/src/test/test1/Howard.java b/src/test/test1/Howard.java index 53bbae8c..6d203808 100644 --- a/src/test/test1/Howard.java +++ b/src/test/test1/Howard.java @@ -21,6 +21,7 @@ class Howard2 { }
public class Howard extends Howard2 {
+ @SuppressWarnings("unused") private Object _remote;
public int run() {
diff --git a/src/test/test1/MySerializableClass.java b/src/test/test1/MySerializableClass.java index 486d1b1b..975dd653 100644 --- a/src/test/test1/MySerializableClass.java +++ b/src/test/test1/MySerializableClass.java @@ -7,6 +7,8 @@ import java.io.*; * @author Bob Lee */ public class MySerializableClass implements Serializable, Cloneable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; String fieldA; String fieldB; diff --git a/src/test/test1/Proceed.java b/src/test/test1/Proceed.java index a37306ef..a55128f6 100644 --- a/src/test/test1/Proceed.java +++ b/src/test/test1/Proceed.java @@ -1,5 +1,6 @@ package test1; +@SuppressWarnings("unused") public class Proceed { public int p(int i, int j) { return i + j; } diff --git a/src/test/test1/RenameClass.java b/src/test/test1/RenameClass.java index 99a92c62..93cfc23e 100644 --- a/src/test/test1/RenameClass.java +++ b/src/test/test1/RenameClass.java @@ -6,6 +6,7 @@ class RenameClass2 { String name; } +@SuppressWarnings({"rawtypes","unchecked", "unused"}) public class RenameClass { private Hashtable table; public RenameClass() { diff --git a/src/test/test2/AddMethod.java b/src/test/test2/AddMethod.java index a7179e6e..c04ff606 100644 --- a/src/test/test2/AddMethod.java +++ b/src/test/test2/AddMethod.java @@ -1,6 +1,7 @@ package test2;
public class AddMethod {
+ @SuppressWarnings("unused") private int f;
public int f() { return 0; }
diff --git a/src/test/test2/Anon.java b/src/test/test2/Anon.java index 56223436..a9c0773f 100644 --- a/src/test/test2/Anon.java +++ b/src/test/test2/Anon.java @@ -1,5 +1,6 @@ package test2;
+@SuppressWarnings("unused") public class Anon {
public Object make() {
return new Object() { int k; };
diff --git a/src/test/test2/Brennan.java b/src/test/test2/Brennan.java index e93e00a9..4cc0a505 100644 --- a/src/test/test2/Brennan.java +++ b/src/test/test2/Brennan.java @@ -1,5 +1,6 @@ package test2; +@SuppressWarnings("unused") public class Brennan { private Object format = null; } diff --git a/src/test/test2/Inner.java b/src/test/test2/Inner.java index dbfb6d6e..15e08663 100644 --- a/src/test/test2/Inner.java +++ b/src/test/test2/Inner.java @@ -1,5 +1,6 @@ package test2; +@SuppressWarnings("unused") public class Inner { public void sample() throws Exception { java.util.Properties props = new java.util.Properties(); diff --git a/src/test/test2/InsertLocal.java b/src/test/test2/InsertLocal.java index d400e622..43794cc8 100644 --- a/src/test/test2/InsertLocal.java +++ b/src/test/test2/InsertLocal.java @@ -22,6 +22,7 @@ public class InsertLocal { return k + s.length(); } + @SuppressWarnings("unused") public int run3() { int i = 0; int j = field; diff --git a/src/test/test2/Nested.java b/src/test/test2/Nested.java index 70ce60ee..6bb4547a 100644 --- a/src/test/test2/Nested.java +++ b/src/test/test2/Nested.java @@ -1,5 +1,6 @@ package test2;
+@SuppressWarnings("unused") public class Nested {
private int i = 3;
private int geti() { return i; }
diff --git a/src/test/test2/Nested2.java b/src/test/test2/Nested2.java index f23439bd..728c1b7a 100644 --- a/src/test/test2/Nested2.java +++ b/src/test/test2/Nested2.java @@ -1,5 +1,6 @@ package test2;
+@SuppressWarnings("unused") public class Nested2 {
private int i = 3;
private double d = 3.0;
diff --git a/src/test/test2/Nested3.java b/src/test/test2/Nested3.java index 570f7a5e..9e9f1ab3 100644 --- a/src/test/test2/Nested3.java +++ b/src/test/test2/Nested3.java @@ -1,5 +1,6 @@ package test2;
+@SuppressWarnings("unused") public class Nested3 {
private int i = 0;
private int geti() { return i; }
diff --git a/src/test/test2/Nested4.java b/src/test/test2/Nested4.java index 5b33aea5..04bcd767 100644 --- a/src/test/test2/Nested4.java +++ b/src/test/test2/Nested4.java @@ -1,5 +1,6 @@ package test2;
+@SuppressWarnings("unused") public class Nested4 {
private static int value = 6;
}
diff --git a/src/test/test2/NewArray.java b/src/test/test2/NewArray.java index d61fa750..f7c0439b 100644 --- a/src/test/test2/NewArray.java +++ b/src/test/test2/NewArray.java @@ -1,5 +1,6 @@ package test2;
+@SuppressWarnings("unused") public class NewArray {
public int run() {
return foo(1);
diff --git a/src/test/test2/NewExprInTry.java b/src/test/test2/NewExprInTry.java index e6e1fe90..70dc9b28 100644 --- a/src/test/test2/NewExprInTry.java +++ b/src/test/test2/NewExprInTry.java @@ -2,12 +2,17 @@ package test2; import java.util.HashMap;
+@SuppressWarnings("rawtypes") class HashMapWrapper extends HashMap {
+ /** default serialVersionUID */
+ private static final long serialVersionUID = 1L;
+
HashMapWrapper(int size, int args) {
super(size);
}
}
+@SuppressWarnings({"rawtypes","unused"}) public class NewExprInTry {
public int run() {
return foo(6);
diff --git a/src/test/test2/NewExprTry.java b/src/test/test2/NewExprTry.java index fb779d96..f728dbe7 100644 --- a/src/test/test2/NewExprTry.java +++ b/src/test/test2/NewExprTry.java @@ -15,6 +15,7 @@ public class NewExprTry { }
public static void main(String[] args) {
+ @SuppressWarnings("unused") NewExprTry obj = new NewExprTry(3);
}
}
diff --git a/src/test/test2/NewOp.java b/src/test/test2/NewOp.java index bf798a92..a9334252 100644 --- a/src/test/test2/NewOp.java +++ b/src/test/test2/NewOp.java @@ -5,6 +5,7 @@ class NewOp2 { }
public class NewOp {
+ @SuppressWarnings("rawtypes") java.util.Vector listenerList;
static int i = 0;
static String s;
diff --git a/src/test/test2/Prune.java b/src/test/test2/Prune.java index 1daf9cbb..f98f7764 100644 --- a/src/test/test2/Prune.java +++ b/src/test/test2/Prune.java @@ -1,6 +1,8 @@ package test2;
public class Prune extends java.awt.Point implements Cloneable, Runnable {
+ /** default serialVersionUID */
+ private static final long serialVersionUID = 1L;
public int value;
public Prune(int i) {
diff --git a/src/test/test3/Enhancer.java b/src/test/test3/Enhancer.java index 8aa13d25..e3a93e8a 100644 --- a/src/test/test3/Enhancer.java +++ b/src/test/test3/Enhancer.java @@ -11,6 +11,7 @@ class EnhanceTest { public void foo(String s) { System.out.println(s); } } +@SuppressWarnings({"rawtypes","unchecked","unused"}) public class Enhancer { private ClassPool pool; private CtClass superClass; diff --git a/src/test/test3/Erasure.java b/src/test/test3/Erasure.java index 412f439a..7514981a 100644 --- a/src/test/test3/Erasure.java +++ b/src/test/test3/Erasure.java @@ -9,6 +9,7 @@ public class Erasure<T> { public Erasure(T t) { value = t; } public Erasure() { value = null; } public int run() { + @SuppressWarnings("unchecked") ErasureGet<String> obj = (ErasureGet<String>)new Erasure<String>("1234"); return obj.get().length(); } diff --git a/src/test/test3/FieldAccessType.java b/src/test/test3/FieldAccessType.java index c61550d6..bb102ba8 100644 --- a/src/test/test3/FieldAccessType.java +++ b/src/test/test3/FieldAccessType.java @@ -4,6 +4,7 @@ public class FieldAccessType { private int[] k; public void access() { k = new int[1]; + @SuppressWarnings("unused") int i = 3; i += k[0]; } diff --git a/src/test/test3/GetMethods.java b/src/test/test3/GetMethods.java index 69cc49fa..64e66bd0 100644 --- a/src/test/test3/GetMethods.java +++ b/src/test/test3/GetMethods.java @@ -1,5 +1,6 @@ package test3; +@SuppressWarnings("unused") class SuperGetMethods { public int f0; protected double d0; @@ -12,6 +13,7 @@ class SuperGetMethods { private void mpri0() {} } +@SuppressWarnings("unused") public class GetMethods extends SuperGetMethods { public GetMethods(int i) {} protected GetMethods(String i, int j) {} diff --git a/src/test/test3/MethodRedirect.java b/src/test/test3/MethodRedirect.java index 889a3c68..c7cacde8 100644 --- a/src/test/test3/MethodRedirect.java +++ b/src/test/test3/MethodRedirect.java @@ -5,6 +5,7 @@ interface MethodRedirectIntf { } public class MethodRedirect implements MethodRedirectIntf { + @SuppressWarnings("unused") private int foo() { return 0; } public static int poi() { return 1; } public int bar() { return 2; } diff --git a/src/test/test3/NestedClass.java b/src/test/test3/NestedClass.java index 75b4efe2..e1459b26 100644 --- a/src/test/test3/NestedClass.java +++ b/src/test/test3/NestedClass.java @@ -17,6 +17,7 @@ public class NestedClass { public Object bar() { class Local { + @SuppressWarnings("unused") int j; } return new Local(); diff --git a/src/test/test3/NewExprTryCatch.java b/src/test/test3/NewExprTryCatch.java index 193985eb..f93b528d 100644 --- a/src/test/test3/NewExprTryCatch.java +++ b/src/test/test3/NewExprTryCatch.java @@ -18,6 +18,7 @@ public class NewExprTryCatch { // the error is somehow related to the string concatenation and local variables, // when the code below is replaced with something else, the error does not occur. String s1 = "a"; + @SuppressWarnings("unused") String s2 = s1 + "b"; } diff --git a/src/test/test3/ReplaceNew.java b/src/test/test3/ReplaceNew.java index 018408eb..8f8a7869 100644 --- a/src/test/test3/ReplaceNew.java +++ b/src/test/test3/ReplaceNew.java @@ -6,6 +6,7 @@ public class ReplaceNew { int i = 0; public int run() { i = 3; + @SuppressWarnings("unused") ReplaceNew s = new ReplaceNew(); new ReplaceNew(); return i; diff --git a/src/test/test3/Visible.java b/src/test/test3/Visible.java index 162f46e1..d3397f1e 100644 --- a/src/test/test3/Visible.java +++ b/src/test/test3/Visible.java @@ -1,5 +1,6 @@ package test3; +@SuppressWarnings("unused") class Visible2 { public int pub; protected int pro; @@ -7,6 +8,7 @@ class Visible2 { int pack; } +@SuppressWarnings("unused") public class Visible { public int pub; protected int pro; diff --git a/src/test/test4/GetAllRefInnerTest.java b/src/test/test4/GetAllRefInnerTest.java index 352b3252..a4921caf 100644 --- a/src/test/test4/GetAllRefInnerTest.java +++ b/src/test/test4/GetAllRefInnerTest.java @@ -20,6 +20,9 @@ public class GetAllRefInnerTest<T> { } public Object foo() { return new java.util.HashSet<String>() { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public String toString() { return this.getClass().toString(); } }; } diff --git a/src/test/test4/JIRA181.java b/src/test/test4/JIRA181.java index c3d2f45a..7c0b0930 100644 --- a/src/test/test4/JIRA181.java +++ b/src/test/test4/JIRA181.java @@ -3,6 +3,9 @@ package test4; import java.util.ArrayList; public class JIRA181<T extends Number> extends ArrayList<T> { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public @interface Condition { Class<? extends ICondition> condition(); } diff --git a/src/test/testproxy/ProxyFactoryPerformanceTest.java b/src/test/testproxy/ProxyFactoryPerformanceTest.java index 55bc7849..df8bd8fc 100644 --- a/src/test/testproxy/ProxyFactoryPerformanceTest.java +++ b/src/test/testproxy/ProxyFactoryPerformanceTest.java @@ -17,6 +17,7 @@ import junit.framework.TestCase; import junit.framework.TestSuite;
import junit.textui.TestRunner;
+@SuppressWarnings({"rawtypes","unchecked", "unused"})
public class ProxyFactoryPerformanceTest extends TestCase {
public static final int COUNT = 100;
@@ -84,6 +85,7 @@ public class ProxyFactoryPerformanceTest extends TestCase { }
}
+@SuppressWarnings({"rawtypes","unused"})
class ProxyMaker extends Thread implements MethodHandler {
private static final MethodFilter FINALIZE_FILTER = new MethodFilter() {
public boolean isHandled(Method m) {
@@ -163,6 +165,9 @@ class EnhancerUser extends Thread implements InvocationHandler { */
class SampleBean implements Serializable {
+ /** default serialVersionUID */
+ private static final long serialVersionUID = 1L;
+
long oid;
int version;
diff --git a/src/test/testproxy/ProxyTester.java b/src/test/testproxy/ProxyTester.java index f325997d..64712ef3 100644 --- a/src/test/testproxy/ProxyTester.java +++ b/src/test/testproxy/ProxyTester.java @@ -3,16 +3,19 @@ package testproxy; import java.lang.reflect.Method; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; + +import org.junit.Assert; + import java.lang.reflect.InvocationTargetException; import javassist.util.proxy.ProxyFactory; import javassist.util.proxy.MethodFilter; import javassist.util.proxy.MethodHandler; import javassist.util.proxy.ProxyObject; import javassist.util.proxy.Proxy; -import junit.framework.Assert; import junit.framework.TestCase; import java.io.*; +@SuppressWarnings({"unchecked", "rawtypes","unused"}) public class ProxyTester extends TestCase { public ProxyTester(String s) { super(s); @@ -398,6 +401,9 @@ public class ProxyTester extends TestCase { } public static class ReadWriteData implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public int foo() { return 4; } } @@ -416,10 +422,16 @@ public class ProxyTester extends TestCase { } public static class WriteReplace implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public Object writeReplace() { return this; } } public static class WriteReplace2 implements Serializable { + /** default serialVersionUID */ + private static final long serialVersionUID = 1L; + public Object writeReplace(int i) { return Integer.valueOf(i); } } diff --git a/src/test/testproxy/Target2.java b/src/test/testproxy/Target2.java index 91b57be5..192bac77 100644 --- a/src/test/testproxy/Target2.java +++ b/src/test/testproxy/Target2.java @@ -2,6 +2,7 @@ package testproxy; import java.io.IOException;
+@SuppressWarnings("unused") public class Target2 {
private int value;
public Target2(int i) { value = 1; }
diff --git a/src/test/testproxy/sub/TargetSuper.java b/src/test/testproxy/sub/TargetSuper.java index 0e40cded..9eb8d1da 100644 --- a/src/test/testproxy/sub/TargetSuper.java +++ b/src/test/testproxy/sub/TargetSuper.java @@ -1,5 +1,6 @@ package testproxy.sub; +@SuppressWarnings("unused") public class TargetSuper { private int poi() { return 1; } int poi2() { return 2; } |