diff options
author | Gary D. Gregory <ggregory@apache.org> | 2016-06-21 20:50:19 +0000 |
---|---|---|
committer | Gary D. Gregory <ggregory@apache.org> | 2016-06-21 20:50:19 +0000 |
commit | 7a28a2d05733714850bd7e51a98fc97c42e47103 (patch) | |
tree | 2fcaa741d928ef61e75c27c17acf5fb6419aaad4 | |
parent | e0522db412e3fce6e5f1e8b965a67c873b2251fe (diff) | |
download | apache-commons-bcel-7a28a2d05733714850bd7e51a98fc97c42e47103.tar.gz |
Use final on local vars when possible (which already do on fields and parameters when possible.)
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/bcel/trunk@1749603 13f79535-47bb-0310-9956-ffa450edef68
160 files changed, 2101 insertions, 2094 deletions
diff --git a/src/main/java/org/apache/bcel/ExceptionConst.java b/src/main/java/org/apache/bcel/ExceptionConst.java index e7fb5c39..efa872ce 100644 --- a/src/main/java/org/apache/bcel/ExceptionConst.java +++ b/src/main/java/org/apache/bcel/ExceptionConst.java @@ -90,8 +90,8 @@ public final class ExceptionConst { // helper method to merge exception class arrays private static Class<?>[] mergeExceptions(final Class<?>[] input, final Class<?> ... extraClasses) { - int extraLen = extraClasses == null ? 0 : extraClasses.length; - Class<?>[] excs = new Class<?>[input.length + extraLen]; + final int extraLen = extraClasses == null ? 0 : extraClasses.length; + final Class<?>[] excs = new Class<?>[input.length + extraLen]; System.arraycopy(input, 0, excs, 0, input.length); if (extraLen > 0) { System.arraycopy(extraClasses, 0, excs, input.length, extraLen); diff --git a/src/main/java/org/apache/bcel/Repository.java b/src/main/java/org/apache/bcel/Repository.java index d8136d27..17a92b53 100644 --- a/src/main/java/org/apache/bcel/Repository.java +++ b/src/main/java/org/apache/bcel/Repository.java @@ -83,12 +83,12 @@ public abstract class Repository { */ public static ClassPath.ClassFile lookupClassFile( final String class_name ) { try { - ClassPath path = repository.getClassPath(); + final ClassPath path = repository.getClassPath(); if (path == null) { return null; } return path.getClassFile(class_name); - } catch (IOException e) { + } catch (final IOException e) { return null; } } @@ -107,7 +107,7 @@ public abstract class Repository { * @return old entry in repository */ public static JavaClass addClass( final JavaClass clazz ) { - JavaClass old = repository.findClass(clazz.getClassName()); + final JavaClass old = repository.findClass(clazz.getClassName()); repository.storeClass(clazz); return old; } @@ -146,7 +146,7 @@ public abstract class Repository { * superclasses can't be found */ public static JavaClass[] getSuperClasses( final String class_name ) throws ClassNotFoundException { - JavaClass jc = lookupClass(class_name); + final JavaClass jc = lookupClass(class_name); return getSuperClasses(jc); } diff --git a/src/main/java/org/apache/bcel/classfile/AnnotationEntry.java b/src/main/java/org/apache/bcel/classfile/AnnotationEntry.java index 8da08b14..1e235bc5 100644 --- a/src/main/java/org/apache/bcel/classfile/AnnotationEntry.java +++ b/src/main/java/org/apache/bcel/classfile/AnnotationEntry.java @@ -138,10 +138,10 @@ public class AnnotationEntry implements Node { final StringBuilder result = new StringBuilder(); result.append("@"); result.append(getAnnotationType()); - ElementValuePair[] evPairs = getElementValuePairs(); + final ElementValuePair[] evPairs = getElementValuePairs(); if (evPairs.length > 0) { result.append("("); - for (ElementValuePair element : evPairs) { + for (final ElementValuePair element : evPairs) { result.append(element.toShortString()); } result.append(")"); @@ -156,10 +156,10 @@ public class AnnotationEntry implements Node { public static AnnotationEntry[] createAnnotationEntries(final Attribute[] attrs) { // Find attributes that contain annotation data - List<AnnotationEntry> accumulatedAnnotations = new ArrayList<>(attrs.length); - for (Attribute attribute : attrs) { + final List<AnnotationEntry> accumulatedAnnotations = new ArrayList<>(attrs.length); + for (final Attribute attribute : attrs) { if (attribute instanceof Annotations) { - Annotations runtimeAnnotations = (Annotations) attribute; + final Annotations runtimeAnnotations = (Annotations) attribute; Collections.addAll(accumulatedAnnotations, runtimeAnnotations.getAnnotationEntries()); } } diff --git a/src/main/java/org/apache/bcel/classfile/Annotations.java b/src/main/java/org/apache/bcel/classfile/Annotations.java index be7ca5b7..561038ac 100644 --- a/src/main/java/org/apache/bcel/classfile/Annotations.java +++ b/src/main/java/org/apache/bcel/classfile/Annotations.java @@ -107,7 +107,7 @@ public abstract class Annotations extends Attribute { return; } dos.writeShort(annotation_table.length); - for (AnnotationEntry element : annotation_table) { + for (final AnnotationEntry element : annotation_table) { element.dump(dos); } } diff --git a/src/main/java/org/apache/bcel/classfile/ArrayElementValue.java b/src/main/java/org/apache/bcel/classfile/ArrayElementValue.java index 0e2e6afe..9e750c4d 100644 --- a/src/main/java/org/apache/bcel/classfile/ArrayElementValue.java +++ b/src/main/java/org/apache/bcel/classfile/ArrayElementValue.java @@ -31,7 +31,7 @@ public class ArrayElementValue extends ElementValue @Override public String toString() { - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); sb.append("{"); for (int i = 0; i < evalues.length; i++) { @@ -59,7 +59,7 @@ public class ArrayElementValue extends ElementValue { dos.writeByte(super.getType()); // u1 type of value (ARRAY == '[') dos.writeShort(evalues.length); - for (ElementValue evalue : evalues) { + for (final ElementValue evalue : evalues) { evalue.dump(dos); } } @@ -67,7 +67,7 @@ public class ArrayElementValue extends ElementValue @Override public String stringifyValue() { - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < evalues.length; i++) { diff --git a/src/main/java/org/apache/bcel/classfile/Attribute.java b/src/main/java/org/apache/bcel/classfile/Attribute.java index 5934f450..b3e62319 100644 --- a/src/main/java/org/apache/bcel/classfile/Attribute.java +++ b/src/main/java/org/apache/bcel/classfile/Attribute.java @@ -185,12 +185,12 @@ public abstract class Attribute implements Cloneable, Node { { byte tag = Const.ATTR_UNKNOWN; // Unknown attribute // Get class name from constant pool via `name_index' indirection - int name_index = file.readUnsignedShort(); - ConstantUtf8 c = (ConstantUtf8) constant_pool.getConstant(name_index, Const.CONSTANT_Utf8); - String name = c.getBytes(); + final int name_index = file.readUnsignedShort(); + final ConstantUtf8 c = (ConstantUtf8) constant_pool.getConstant(name_index, Const.CONSTANT_Utf8); + final String name = c.getBytes(); // Length of data in bytes - int length = file.readInt(); + final int length = file.readInt(); // Compare strings to find known attribute for (byte i = 0; i < Const.KNOWN_ATTRIBUTES; i++) @@ -206,7 +206,7 @@ public abstract class Attribute implements Cloneable, Node { switch (tag) { case Const.ATTR_UNKNOWN: - Object r = readers.get(name); + final Object r = readers.get(name); if (r instanceof UnknownAttributeReader) { return ((UnknownAttributeReader) r).createAttribute(name_index, length, file, constant_pool); @@ -268,7 +268,7 @@ public abstract class Attribute implements Cloneable, Node { */ public String getName() { - ConstantUtf8 c = (ConstantUtf8) constant_pool.getConstant(name_index, Const.CONSTANT_Utf8); + final ConstantUtf8 c = (ConstantUtf8) constant_pool.getConstant(name_index, Const.CONSTANT_Utf8); return c.getBytes(); } @@ -344,7 +344,7 @@ public abstract class Attribute implements Cloneable, Node { { attr = (Attribute) super.clone(); } - catch (CloneNotSupportedException e) + catch (final CloneNotSupportedException e) { throw new Error("Clone Not Supported"); // never happens } diff --git a/src/main/java/org/apache/bcel/classfile/BootstrapMethod.java b/src/main/java/org/apache/bcel/classfile/BootstrapMethod.java index 66296cfb..7313048a 100644 --- a/src/main/java/org/apache/bcel/classfile/BootstrapMethod.java +++ b/src/main/java/org/apache/bcel/classfile/BootstrapMethod.java @@ -125,7 +125,7 @@ public class BootstrapMethod implements Cloneable { * @return Resolved string representation */ public final String toString( final ConstantPool constant_pool ) { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); String bootstrap_method_name; bootstrap_method_name = constant_pool.constantToString(bootstrap_method_ref, Const.CONSTANT_MethodHandle); @@ -150,7 +150,7 @@ public class BootstrapMethod implements Cloneable { public final void dump(final DataOutputStream file) throws IOException { file.writeShort(bootstrap_method_ref); file.writeShort(bootstrap_arguments.length); - for (int bootstrap_argument : bootstrap_arguments) { + for (final int bootstrap_argument : bootstrap_arguments) { file.writeShort(bootstrap_argument); } } @@ -161,7 +161,7 @@ public class BootstrapMethod implements Cloneable { public BootstrapMethod copy() { try { return (BootstrapMethod) clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { // TODO should this throw? } return null; diff --git a/src/main/java/org/apache/bcel/classfile/BootstrapMethods.java b/src/main/java/org/apache/bcel/classfile/BootstrapMethods.java index 4aa090ff..acc17fb8 100644 --- a/src/main/java/org/apache/bcel/classfile/BootstrapMethods.java +++ b/src/main/java/org/apache/bcel/classfile/BootstrapMethods.java @@ -66,7 +66,7 @@ public class BootstrapMethods extends Attribute { BootstrapMethods(final int name_index, final int length, final DataInput input, final ConstantPool constant_pool) throws IOException { this(name_index, length, (BootstrapMethod[]) null, constant_pool); - int num_bootstrap_methods = input.readUnsignedShort(); + final int num_bootstrap_methods = input.readUnsignedShort(); bootstrap_methods = new BootstrapMethod[num_bootstrap_methods]; for (int i = 0; i < num_bootstrap_methods; i++) { bootstrap_methods[i] = new BootstrapMethod(input); @@ -100,7 +100,7 @@ public class BootstrapMethods extends Attribute { */ @Override public BootstrapMethods copy(final ConstantPool _constant_pool) { - BootstrapMethods c = (BootstrapMethods) clone(); + final BootstrapMethods c = (BootstrapMethods) clone(); c.bootstrap_methods = new BootstrapMethod[bootstrap_methods.length]; for (int i = 0; i < bootstrap_methods.length; i++) { @@ -121,7 +121,7 @@ public class BootstrapMethods extends Attribute { super.dump(file); file.writeShort(bootstrap_methods.length); - for (BootstrapMethod bootstrap_method : bootstrap_methods) { + for (final BootstrapMethod bootstrap_method : bootstrap_methods) { bootstrap_method.dump(file); } } @@ -131,7 +131,7 @@ public class BootstrapMethods extends Attribute { */ @Override public final String toString() { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); buf.append("BootstrapMethods("); buf.append(bootstrap_methods.length); buf.append("):\n"); diff --git a/src/main/java/org/apache/bcel/classfile/ClassElementValue.java b/src/main/java/org/apache/bcel/classfile/ClassElementValue.java index af2783d9..2a62a872 100644 --- a/src/main/java/org/apache/bcel/classfile/ClassElementValue.java +++ b/src/main/java/org/apache/bcel/classfile/ClassElementValue.java @@ -45,7 +45,7 @@ public class ClassElementValue extends ElementValue public String getClassString() { - ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(idx, + final ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(idx, Const.CONSTANT_Utf8); return c.getBytes(); } @@ -53,7 +53,7 @@ public class ClassElementValue extends ElementValue @Override public String stringifyValue() { - ConstantUtf8 cu8 = (ConstantUtf8) super.getConstantPool().getConstant(idx, + final ConstantUtf8 cu8 = (ConstantUtf8) super.getConstantPool().getConstant(idx, Const.CONSTANT_Utf8); return cu8.getBytes(); } diff --git a/src/main/java/org/apache/bcel/classfile/ClassParser.java b/src/main/java/org/apache/bcel/classfile/ClassParser.java index 28eeb68a..394b8e9b 100644 --- a/src/main/java/org/apache/bcel/classfile/ClassParser.java +++ b/src/main/java/org/apache/bcel/classfile/ClassParser.java @@ -70,7 +70,7 @@ public final class ClassParser { public ClassParser(final InputStream inputStream, final String file_name) { this.file_name = file_name; fileOwned = false; - String clazz = inputStream.getClass().getName(); // Not a very clean solution ... + final String clazz = inputStream.getClass().getName(); // Not a very clean solution ... is_zip = clazz.startsWith("java.util.zip.") || clazz.startsWith("java.util.jar."); if (inputStream instanceof DataInputStream) { this.dataInputStream = (DataInputStream) inputStream; @@ -121,7 +121,7 @@ public final class ClassParser { if (fileOwned) { if (is_zip) { zip = new ZipFile(zip_file); - ZipEntry entry = zip.getEntry(file_name); + final ZipEntry entry = zip.getEntry(file_name); if (entry == null) { throw new IOException("File " + file_name + " not found"); @@ -174,7 +174,7 @@ public final class ClassParser { if (dataInputStream != null) { dataInputStream.close(); } - } catch (IOException ioe) { + } catch (final IOException ioe) { //ignore close exceptions } } @@ -182,7 +182,7 @@ public final class ClassParser { if (zip != null) { zip.close(); } - } catch (IOException ioe) { + } catch (final IOException ioe) { //ignore close exceptions } } @@ -200,7 +200,7 @@ public final class ClassParser { * @throws ClassFormatException */ private void readAttributes() throws IOException, ClassFormatException { - int attributes_count = dataInputStream.readUnsignedShort(); + final int attributes_count = dataInputStream.readUnsignedShort(); attributes = new Attribute[attributes_count]; for (int i = 0; i < attributes_count; i++) { attributes[i] = Attribute.readAttribute(dataInputStream, constant_pool); @@ -246,7 +246,7 @@ public final class ClassParser { * @throws ClassFormatException */ private void readFields() throws IOException, ClassFormatException { - int fields_count = dataInputStream.readUnsignedShort(); + final int fields_count = dataInputStream.readUnsignedShort(); fields = new Field[fields_count]; for (int i = 0; i < fields_count; i++) { fields[i] = new Field(dataInputStream, constant_pool); @@ -274,7 +274,7 @@ public final class ClassParser { * @throws ClassFormatException */ private void readInterfaces() throws IOException, ClassFormatException { - int interfaces_count = dataInputStream.readUnsignedShort(); + final int interfaces_count = dataInputStream.readUnsignedShort(); interfaces = new int[interfaces_count]; for (int i = 0; i < interfaces_count; i++) { interfaces[i] = dataInputStream.readUnsignedShort(); @@ -288,7 +288,7 @@ public final class ClassParser { * @throws ClassFormatException */ private void readMethods() throws IOException, ClassFormatException { - int methods_count = dataInputStream.readUnsignedShort(); + final int methods_count = dataInputStream.readUnsignedShort(); methods = new Method[methods_count]; for (int i = 0; i < methods_count; i++) { methods[i] = new Method(dataInputStream, constant_pool); diff --git a/src/main/java/org/apache/bcel/classfile/Code.java b/src/main/java/org/apache/bcel/classfile/Code.java index 50da232f..53f3d4b0 100644 --- a/src/main/java/org/apache/bcel/classfile/Code.java +++ b/src/main/java/org/apache/bcel/classfile/Code.java @@ -71,13 +71,13 @@ public final class Code extends Attribute { // Initialize with some default values which will be overwritten later this(name_index, length, file.readUnsignedShort(), file.readUnsignedShort(), (byte[]) null, (CodeException[]) null, (Attribute[]) null, constant_pool); - int code_length = file.readInt(); + final int code_length = file.readInt(); code = new byte[code_length]; // Read byte code file.readFully(code); /* Read exception table that contains all regions where an exception * handler is active, i.e., a try { ... } catch() block. */ - int exception_table_length = file.readUnsignedShort(); + final int exception_table_length = file.readUnsignedShort(); exception_table = new CodeException[exception_table_length]; for (int i = 0; i < exception_table_length; i++) { exception_table[i] = new CodeException(file); @@ -85,7 +85,7 @@ public final class Code extends Attribute { /* Read all attributes, currently `LineNumberTable' and * `LocalVariableTable' */ - int attributes_count = file.readUnsignedShort(); + final int attributes_count = file.readUnsignedShort(); attributes = new Attribute[attributes_count]; for (int i = 0; i < attributes_count; i++) { attributes[i] = Attribute.readAttribute(file, constant_pool); @@ -147,11 +147,11 @@ public final class Code extends Attribute { file.writeInt(code.length); file.write(code, 0, code.length); file.writeShort(exception_table.length); - for (CodeException exception : exception_table) { + for (final CodeException exception : exception_table) { exception.dump(file); } file.writeShort(attributes.length); - for (Attribute attribute : attributes) { + for (final Attribute attribute : attributes) { attribute.dump(file); } } @@ -170,7 +170,7 @@ public final class Code extends Attribute { * @return LineNumberTable of Code, if it has one */ public LineNumberTable getLineNumberTable() { - for (Attribute attribute : attributes) { + for (final Attribute attribute : attributes) { if (attribute instanceof LineNumberTable) { return (LineNumberTable) attribute; } @@ -183,7 +183,7 @@ public final class Code extends Attribute { * @return LocalVariableTable of Code, if it has one */ public LocalVariableTable getLocalVariableTable() { - for (Attribute attribute : attributes) { + for (final Attribute attribute : attributes) { if (attribute instanceof LocalVariableTable) { return (LocalVariableTable) attribute; } @@ -245,7 +245,7 @@ public final class Code extends Attribute { private int calculateLength() { int len = 0; if (attributes != null) { - for (Attribute attribute : attributes) { + for (final Attribute attribute : attributes) { len += attribute.getLength() + 6 /*attribute header size*/; } } @@ -300,19 +300,19 @@ public final class Code extends Attribute { * @return String representation of code chunk. */ public final String toString( final boolean verbose ) { - StringBuilder buf = new StringBuilder(100); // CHECKSTYLE IGNORE MagicNumber + final StringBuilder buf = new StringBuilder(100); // CHECKSTYLE IGNORE MagicNumber buf.append("Code(max_stack = ").append(max_stack).append(", max_locals = ").append( max_locals).append(", code_length = ").append(code.length).append(")\n").append( Utility.codeToString(code, super.getConstantPool(), 0, -1, verbose)); if (exception_table.length > 0) { buf.append("\nException handler(s) = \n").append("From\tTo\tHandler\tType\n"); - for (CodeException exception : exception_table) { + for (final CodeException exception : exception_table) { buf.append(exception.toString(super.getConstantPool(), verbose)).append("\n"); } } if (attributes.length > 0) { buf.append("\nAttribute(s) = "); - for (Attribute attribute : attributes) { + for (final Attribute attribute : attributes) { buf.append("\n").append(attribute); } } @@ -336,7 +336,7 @@ public final class Code extends Attribute { */ @Override public Attribute copy( final ConstantPool _constant_pool ) { - Code c = (Code) clone(); + final Code c = (Code) clone(); if (code != null) { c.code = new byte[code.length]; System.arraycopy(code, 0, c.code, 0, code.length); diff --git a/src/main/java/org/apache/bcel/classfile/CodeException.java b/src/main/java/org/apache/bcel/classfile/CodeException.java index dd73596e..8c1c5a4c 100644 --- a/src/main/java/org/apache/bcel/classfile/CodeException.java +++ b/src/main/java/org/apache/bcel/classfile/CodeException.java @@ -210,7 +210,7 @@ public final class CodeException implements Cloneable, Node, Constants { public CodeException copy() { try { return (CodeException) clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { // TODO should this throw? } return null; diff --git a/src/main/java/org/apache/bcel/classfile/Constant.java b/src/main/java/org/apache/bcel/classfile/Constant.java index 649bd222..1f0bbf2d 100644 --- a/src/main/java/org/apache/bcel/classfile/Constant.java +++ b/src/main/java/org/apache/bcel/classfile/Constant.java @@ -37,15 +37,15 @@ public abstract class Constant implements Cloneable, Node { @Override public boolean equals( final Object o1, final Object o2 ) { - Constant THIS = (Constant) o1; - Constant THAT = (Constant) o2; + final Constant THIS = (Constant) o1; + final Constant THAT = (Constant) o2; return THIS.toString().equals(THAT.toString()); } @Override public int hashCode( final Object o ) { - Constant THIS = (Constant) o; + final Constant THIS = (Constant) o; return THIS.toString().hashCode(); } }; @@ -107,7 +107,7 @@ public abstract class Constant implements Cloneable, Node { public Constant copy() { try { return (Constant) super.clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { // TODO should this throw? } return null; @@ -118,7 +118,7 @@ public abstract class Constant implements Cloneable, Node { public Object clone() { try { return super.clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { throw new Error("Clone Not Supported"); // never happens } } @@ -133,7 +133,7 @@ public abstract class Constant implements Cloneable, Node { */ public static Constant readConstant( final DataInput input ) throws IOException, ClassFormatException { - byte b = input.readByte(); // Read tag byte + final byte b = input.readByte(); // Read tag byte switch (b) { case Const.CONSTANT_Class: return new ConstantClass(input); diff --git a/src/main/java/org/apache/bcel/classfile/ConstantClass.java b/src/main/java/org/apache/bcel/classfile/ConstantClass.java index fdb863f4..81725e1b 100644 --- a/src/main/java/org/apache/bcel/classfile/ConstantClass.java +++ b/src/main/java/org/apache/bcel/classfile/ConstantClass.java @@ -110,7 +110,7 @@ public final class ConstantClass extends Constant implements ConstantObject { */ @Override public Object getConstantValue( final ConstantPool cp ) { - Constant c = cp.getConstant(name_index, Const.CONSTANT_Utf8); + final Constant c = cp.getConstant(name_index, Const.CONSTANT_Utf8); return ((ConstantUtf8) c).getBytes(); } diff --git a/src/main/java/org/apache/bcel/classfile/ConstantPool.java b/src/main/java/org/apache/bcel/classfile/ConstantPool.java index 99ddc08a..d9f9f8a5 100644 --- a/src/main/java/org/apache/bcel/classfile/ConstantPool.java +++ b/src/main/java/org/apache/bcel/classfile/ConstantPool.java @@ -57,7 +57,7 @@ public class ConstantPool implements Cloneable, Node { */ public ConstantPool(final DataInput input) throws IOException, ClassFormatException { byte tag; - int constant_pool_count = input.readUnsignedShort(); + final int constant_pool_count = input.readUnsignedShort(); constant_pool = new Constant[constant_pool_count]; /* constant_pool[0] is unused by the compiler and may be used freely * by the implementation. @@ -101,7 +101,7 @@ public class ConstantPool implements Cloneable, Node { public String constantToString( Constant c ) throws ClassFormatException { String str; int i; - byte tag = c.getTag(); + final byte tag = c.getTag(); switch (tag) { case Const.CONSTANT_Class: i = ((ConstantClass) c).getNameIndex(); @@ -144,17 +144,17 @@ public class ConstantPool implements Cloneable, Node { case Const.CONSTANT_MethodHandle: // Note that the ReferenceIndex may point to a Fieldref, Methodref or // InterfaceMethodref - so we need to peek ahead to get the actual type. - ConstantMethodHandle cmh = (ConstantMethodHandle) c; + final ConstantMethodHandle cmh = (ConstantMethodHandle) c; str = Const.getMethodHandleName(cmh.getReferenceKind()) + " " + constantToString(cmh.getReferenceIndex(), getConstant(cmh.getReferenceIndex()).getTag()); break; case Const.CONSTANT_MethodType: - ConstantMethodType cmt = (ConstantMethodType) c; + final ConstantMethodType cmt = (ConstantMethodType) c; str = constantToString(cmt.getDescriptorIndex(), Const.CONSTANT_Utf8); break; case Const.CONSTANT_InvokeDynamic: - ConstantInvokeDynamic cid = (ConstantInvokeDynamic) c; + final ConstantInvokeDynamic cid = (ConstantInvokeDynamic) c; str = cid.getBootstrapMethodAttrIndex() + ":" + constantToString(cid.getNameAndTypeIndex(), Const.CONSTANT_NameAndType); @@ -167,9 +167,9 @@ public class ConstantPool implements Cloneable, Node { private static String escape( final String str ) { - int len = str.length(); - StringBuilder buf = new StringBuilder(len + 5); - char[] ch = str.toCharArray(); + final int len = str.length(); + final StringBuilder buf = new StringBuilder(len + 5); + final char[] ch = str.toCharArray(); for (int i = 0; i < len; i++) { switch (ch[i]) { case '\n': @@ -204,7 +204,7 @@ public class ConstantPool implements Cloneable, Node { * @return String representation */ public String constantToString( final int index, final byte tag ) throws ClassFormatException { - Constant c = getConstant(index, tag); + final Constant c = getConstant(index, tag); return constantToString(c); } @@ -343,7 +343,7 @@ public class ConstantPool implements Cloneable, Node { */ @Override public String toString() { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); for (int i = 1; i < constant_pool.length; i++) { buf.append(i).append(")").append(constant_pool[i]).append("\n"); } @@ -364,7 +364,7 @@ public class ConstantPool implements Cloneable, Node { c.constant_pool[i] = constant_pool[i].copy(); } } - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { // TODO should this throw? } return c; diff --git a/src/main/java/org/apache/bcel/classfile/ConstantString.java b/src/main/java/org/apache/bcel/classfile/ConstantString.java index dc675c89..2e4b223e 100644 --- a/src/main/java/org/apache/bcel/classfile/ConstantString.java +++ b/src/main/java/org/apache/bcel/classfile/ConstantString.java @@ -118,7 +118,7 @@ public final class ConstantString extends Constant implements ConstantObject { */ @Override public Object getConstantValue( final ConstantPool cp ) { - Constant c = cp.getConstant(string_index, Const.CONSTANT_Utf8); + final Constant c = cp.getConstant(string_index, Const.CONSTANT_Utf8); return ((ConstantUtf8) c).getBytes(); } diff --git a/src/main/java/org/apache/bcel/classfile/ConstantValue.java b/src/main/java/org/apache/bcel/classfile/ConstantValue.java index e476f3b8..1c2f289d 100644 --- a/src/main/java/org/apache/bcel/classfile/ConstantValue.java +++ b/src/main/java/org/apache/bcel/classfile/ConstantValue.java @@ -153,7 +153,7 @@ public final class ConstantValue extends Attribute { */ @Override public Attribute copy( final ConstantPool _constant_pool ) { - ConstantValue c = (ConstantValue) clone(); + final ConstantValue c = (ConstantValue) clone(); c.setConstantPool(_constant_pool); return c; } diff --git a/src/main/java/org/apache/bcel/classfile/Deprecated.java b/src/main/java/org/apache/bcel/classfile/Deprecated.java index 03f49384..d84ddb7c 100644 --- a/src/main/java/org/apache/bcel/classfile/Deprecated.java +++ b/src/main/java/org/apache/bcel/classfile/Deprecated.java @@ -135,7 +135,7 @@ public final class Deprecated extends Attribute { */ @Override public Attribute copy( final ConstantPool _constant_pool ) { - Deprecated c = (Deprecated) clone(); + final Deprecated c = (Deprecated) clone(); if (bytes != null) { c.bytes = new byte[bytes.length]; System.arraycopy(bytes, 0, c.bytes, 0, bytes.length); diff --git a/src/main/java/org/apache/bcel/classfile/DescendingVisitor.java b/src/main/java/org/apache/bcel/classfile/DescendingVisitor.java index 7526c21d..2eab3fa9 100644 --- a/src/main/java/org/apache/bcel/classfile/DescendingVisitor.java +++ b/src/main/java/org/apache/bcel/classfile/DescendingVisitor.java @@ -49,7 +49,7 @@ public class DescendingVisitor implements Visitor */ public Object predecessor(final int level) { - int size = stack.size(); + final int size = stack.size(); if ((size < 2) || (level < 0)) { return null; @@ -90,16 +90,16 @@ public class DescendingVisitor implements Visitor { stack.push(_clazz); _clazz.accept(visitor); - Field[] fields = _clazz.getFields(); - for (Field field : fields) { + final Field[] fields = _clazz.getFields(); + for (final Field field : fields) { field.accept(this); } - Method[] methods = _clazz.getMethods(); - for (Method method : methods) { + final Method[] methods = _clazz.getMethods(); + for (final Method method : methods) { method.accept(this); } - Attribute[] attributes = _clazz.getAttributes(); - for (Attribute attribute : attributes) { + final Attribute[] attributes = _clazz.getAttributes(); + for (final Attribute attribute : attributes) { attribute.accept(this); } _clazz.getConstantPool().accept(this); @@ -114,8 +114,8 @@ public class DescendingVisitor implements Visitor { stack.push(annotation); annotation.accept(visitor); - AnnotationEntry[] entries = annotation.getAnnotationEntries(); - for (AnnotationEntry entrie : entries) { + final AnnotationEntry[] entries = annotation.getAnnotationEntries(); + for (final AnnotationEntry entrie : entries) { entrie.accept(this); } stack.pop(); @@ -137,8 +137,8 @@ public class DescendingVisitor implements Visitor { stack.push(field); field.accept(visitor); - Attribute[] attributes = field.getAttributes(); - for (Attribute attribute : attributes) { + final Attribute[] attributes = field.getAttributes(); + for (final Attribute attribute : attributes) { attribute.accept(this); } stack.pop(); @@ -157,8 +157,8 @@ public class DescendingVisitor implements Visitor { stack.push(method); method.accept(visitor); - Attribute[] attributes = method.getAttributes(); - for (Attribute attribute : attributes) { + final Attribute[] attributes = method.getAttributes(); + for (final Attribute attribute : attributes) { attribute.accept(this); } stack.pop(); @@ -177,12 +177,12 @@ public class DescendingVisitor implements Visitor { stack.push(code); code.accept(visitor); - CodeException[] table = code.getExceptionTable(); - for (CodeException element : table) { + final CodeException[] table = code.getExceptionTable(); + for (final CodeException element : table) { element.accept(this); } - Attribute[] attributes = code.getAttributes(); - for (Attribute attribute : attributes) { + final Attribute[] attributes = code.getAttributes(); + for (final Attribute attribute : attributes) { attribute.accept(this); } stack.pop(); @@ -201,8 +201,8 @@ public class DescendingVisitor implements Visitor { stack.push(table); table.accept(visitor); - LineNumber[] numbers = table.getLineNumberTable(); - for (LineNumber number : numbers) { + final LineNumber[] numbers = table.getLineNumberTable(); + for (final LineNumber number : numbers) { number.accept(this); } stack.pop(); @@ -221,8 +221,8 @@ public class DescendingVisitor implements Visitor { stack.push(table); table.accept(visitor); - LocalVariable[] vars = table.getLocalVariableTable(); - for (LocalVariable var : vars) { + final LocalVariable[] vars = table.getLocalVariableTable(); + for (final LocalVariable var : vars) { var.accept(this); } stack.pop(); @@ -233,8 +233,8 @@ public class DescendingVisitor implements Visitor { stack.push(table); table.accept(visitor); - StackMapEntry[] vars = table.getStackMap(); - for (StackMapEntry var : vars) { + final StackMapEntry[] vars = table.getStackMap(); + for (final StackMapEntry var : vars) { var.accept(this); } stack.pop(); @@ -261,7 +261,7 @@ public class DescendingVisitor implements Visitor { stack.push(cp); cp.accept(visitor); - Constant[] constants = cp.getConstantPool(); + final Constant[] constants = cp.getConstantPool(); for (int i = 1; i < constants.length; i++) { if (constants[i] != null) @@ -378,8 +378,8 @@ public class DescendingVisitor implements Visitor { stack.push(ic); ic.accept(visitor); - InnerClass[] ics = ic.getInnerClasses(); - for (InnerClass ic2 : ics) { + final InnerClass[] ics = ic.getInnerClasses(); + for (final InnerClass ic2 : ics) { ic2.accept(this); } stack.pop(); diff --git a/src/main/java/org/apache/bcel/classfile/ElementValue.java b/src/main/java/org/apache/bcel/classfile/ElementValue.java index 573297a3..1dcad244 100644 --- a/src/main/java/org/apache/bcel/classfile/ElementValue.java +++ b/src/main/java/org/apache/bcel/classfile/ElementValue.java @@ -76,7 +76,7 @@ public abstract class ElementValue public static ElementValue readElementValue(final DataInput input, final ConstantPool cpool) throws IOException { - byte type = input.readByte(); + final byte type = input.readByte(); switch (type) { case PRIMITIVE_BYTE: @@ -101,8 +101,8 @@ public abstract class ElementValue return new AnnotationElementValue(ANNOTATION, AnnotationEntry.read(input, cpool, false), cpool); case ARRAY: - int numArrayVals = input.readUnsignedShort(); - ElementValue[] evalues = new ElementValue[numArrayVals]; + final int numArrayVals = input.readUnsignedShort(); + final ElementValue[] evalues = new ElementValue[numArrayVals]; for (int j = 0; j < numArrayVals; j++) { evalues[j] = ElementValue.readElementValue(input, cpool); diff --git a/src/main/java/org/apache/bcel/classfile/ElementValuePair.java b/src/main/java/org/apache/bcel/classfile/ElementValuePair.java index c1564e92..cfdcd18e 100644 --- a/src/main/java/org/apache/bcel/classfile/ElementValuePair.java +++ b/src/main/java/org/apache/bcel/classfile/ElementValuePair.java @@ -46,7 +46,7 @@ public class ElementValuePair public String getNameString() { - ConstantUtf8 c = (ConstantUtf8) constantPool.getConstant( + final ConstantUtf8 c = (ConstantUtf8) constantPool.getConstant( elementNameIndex, Const.CONSTANT_Utf8); return c.getBytes(); } @@ -63,7 +63,7 @@ public class ElementValuePair public String toShortString() { - StringBuilder result = new StringBuilder(); + final StringBuilder result = new StringBuilder(); result.append(getNameString()).append("=").append( getValue().toShortString()); return result.toString(); diff --git a/src/main/java/org/apache/bcel/classfile/EnclosingMethod.java b/src/main/java/org/apache/bcel/classfile/EnclosingMethod.java index b02e1461..02e962b4 100644 --- a/src/main/java/org/apache/bcel/classfile/EnclosingMethod.java +++ b/src/main/java/org/apache/bcel/classfile/EnclosingMethod.java @@ -83,7 +83,7 @@ public class EnclosingMethod extends Attribute { } public final ConstantClass getEnclosingClass() { - ConstantClass c = + final ConstantClass c = (ConstantClass)super.getConstantPool().getConstant(classIndex,Const.CONSTANT_Class); return c; } @@ -92,7 +92,7 @@ public class EnclosingMethod extends Attribute { if (methodIndex == 0) { return null; } - ConstantNameAndType nat = + final ConstantNameAndType nat = (ConstantNameAndType)super.getConstantPool().getConstant(methodIndex,Const.CONSTANT_NameAndType); return nat; } diff --git a/src/main/java/org/apache/bcel/classfile/EnumElementValue.java b/src/main/java/org/apache/bcel/classfile/EnumElementValue.java index 5b7045f8..4bab0a81 100644 --- a/src/main/java/org/apache/bcel/classfile/EnumElementValue.java +++ b/src/main/java/org/apache/bcel/classfile/EnumElementValue.java @@ -55,21 +55,21 @@ public class EnumElementValue extends ElementValue @Override public String stringifyValue() { - ConstantUtf8 cu8 = (ConstantUtf8) super.getConstantPool().getConstant(valueIdx, + final ConstantUtf8 cu8 = (ConstantUtf8) super.getConstantPool().getConstant(valueIdx, Const.CONSTANT_Utf8); return cu8.getBytes(); } public String getEnumTypeString() { - ConstantUtf8 cu8 = (ConstantUtf8) super.getConstantPool().getConstant(typeIdx, + final ConstantUtf8 cu8 = (ConstantUtf8) super.getConstantPool().getConstant(typeIdx, Const.CONSTANT_Utf8); return cu8.getBytes();// Utility.signatureToString(cu8.getBytes()); } public String getEnumValueString() { - ConstantUtf8 cu8 = (ConstantUtf8) super.getConstantPool().getConstant(valueIdx, + final ConstantUtf8 cu8 = (ConstantUtf8) super.getConstantPool().getConstant(valueIdx, Const.CONSTANT_Utf8); return cu8.getBytes(); } diff --git a/src/main/java/org/apache/bcel/classfile/ExceptionTable.java b/src/main/java/org/apache/bcel/classfile/ExceptionTable.java index 5feb9762..06b46bf6 100644 --- a/src/main/java/org/apache/bcel/classfile/ExceptionTable.java +++ b/src/main/java/org/apache/bcel/classfile/ExceptionTable.java @@ -71,7 +71,7 @@ public final class ExceptionTable extends Attribute { */ ExceptionTable(final int name_index, final int length, final DataInput input, final ConstantPool constant_pool) throws IOException { this(name_index, length, (int[]) null, constant_pool); - int number_of_exceptions = input.readUnsignedShort(); + final int number_of_exceptions = input.readUnsignedShort(); exception_index_table = new int[number_of_exceptions]; for (int i = 0; i < number_of_exceptions; i++) { exception_index_table[i] = input.readUnsignedShort(); @@ -102,7 +102,7 @@ public final class ExceptionTable extends Attribute { public final void dump( final DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(exception_index_table.length); - for (int index : exception_index_table) { + for (final int index : exception_index_table) { file.writeShort(index); } } @@ -128,7 +128,7 @@ public final class ExceptionTable extends Attribute { * @return class names of thrown exceptions */ public final String[] getExceptionNames() { - String[] names = new String[exception_index_table.length]; + final String[] names = new String[exception_index_table.length]; for (int i = 0; i < exception_index_table.length; i++) { names[i] = super.getConstantPool().getConstantString(exception_index_table[i], Const.CONSTANT_Class).replace('/', '.'); @@ -151,7 +151,7 @@ public final class ExceptionTable extends Attribute { */ @Override public final String toString() { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); String str; buf.append("Exceptions: "); for (int i = 0; i < exception_index_table.length; i++) { @@ -170,7 +170,7 @@ public final class ExceptionTable extends Attribute { */ @Override public Attribute copy( final ConstantPool _constant_pool ) { - ExceptionTable c = (ExceptionTable) clone(); + final ExceptionTable c = (ExceptionTable) clone(); if (exception_index_table != null) { c.exception_index_table = new int[exception_index_table.length]; System.arraycopy(exception_index_table, 0, c.exception_index_table, 0, diff --git a/src/main/java/org/apache/bcel/classfile/Field.java b/src/main/java/org/apache/bcel/classfile/Field.java index 50c06d3f..e7ba578c 100644 --- a/src/main/java/org/apache/bcel/classfile/Field.java +++ b/src/main/java/org/apache/bcel/classfile/Field.java @@ -36,8 +36,8 @@ public final class Field extends FieldOrMethod { @Override public boolean equals( final Object o1, final Object o2 ) { - Field THIS = (Field) o1; - Field THAT = (Field) o2; + final Field THIS = (Field) o1; + final Field THAT = (Field) o2; return THIS.getName().equals(THAT.getName()) && THIS.getSignature().equals(THAT.getSignature()); } @@ -45,7 +45,7 @@ public final class Field extends FieldOrMethod { @Override public int hashCode( final Object o ) { - Field THIS = (Field) o; + final Field THIS = (Field) o; return THIS.getSignature().hashCode() ^ THIS.getName().hashCode(); } }; @@ -100,7 +100,7 @@ public final class Field extends FieldOrMethod { * @return constant value associated with this field (may be null) */ public final ConstantValue getConstantValue() { - for (Attribute attribute : super.getAttributes()) { + for (final Attribute attribute : super.getAttributes()) { if (attribute.getTag() == Const.ATTR_CONSTANT_VALUE) { return (ConstantValue) attribute; } @@ -126,13 +126,13 @@ public final class Field extends FieldOrMethod { access = access.isEmpty() ? "" : (access + " "); signature = Utility.signatureToString(getSignature()); name = getName(); - StringBuilder buf = new StringBuilder(64); // CHECKSTYLE IGNORE MagicNumber + final StringBuilder buf = new StringBuilder(64); // CHECKSTYLE IGNORE MagicNumber buf.append(access).append(signature).append(" ").append(name); - ConstantValue cv = getConstantValue(); + final ConstantValue cv = getConstantValue(); if (cv != null) { buf.append(" = ").append(cv); } - for (Attribute attribute : super.getAttributes()) { + for (final Attribute attribute : super.getAttributes()) { if (!(attribute instanceof ConstantValue)) { buf.append(" [").append(attribute).append("]"); } diff --git a/src/main/java/org/apache/bcel/classfile/FieldOrMethod.java b/src/main/java/org/apache/bcel/classfile/FieldOrMethod.java index dc8dc246..81c602bf 100644 --- a/src/main/java/org/apache/bcel/classfile/FieldOrMethod.java +++ b/src/main/java/org/apache/bcel/classfile/FieldOrMethod.java @@ -103,7 +103,7 @@ public abstract class FieldOrMethod extends AccessFlags implements Cloneable, No protected FieldOrMethod(final DataInput file, final ConstantPool constant_pool) throws IOException, ClassFormatException { this(file.readUnsignedShort(), file.readUnsignedShort(), file.readUnsignedShort(), null, constant_pool); - int attributes_count = file.readUnsignedShort(); + final int attributes_count = file.readUnsignedShort(); attributes = new Attribute[attributes_count]; for (int i = 0; i < attributes_count; i++) { attributes[i] = Attribute.readAttribute(file, constant_pool); @@ -140,7 +140,7 @@ public abstract class FieldOrMethod extends AccessFlags implements Cloneable, No file.writeShort(name_index); file.writeShort(signature_index); file.writeShort(attributes.length); - for (Attribute attribute : attributes) { + for (final Attribute attribute : attributes) { attribute.dump(file); } } @@ -239,7 +239,7 @@ public abstract class FieldOrMethod extends AccessFlags implements Cloneable, No try { c = (FieldOrMethod)clone(); - } catch(CloneNotSupportedException e) { + } catch(final CloneNotSupportedException e) { // ignored, but will cause NPE ... } diff --git a/src/main/java/org/apache/bcel/classfile/InnerClass.java b/src/main/java/org/apache/bcel/classfile/InnerClass.java index feba4a9e..777facc2 100644 --- a/src/main/java/org/apache/bcel/classfile/InnerClass.java +++ b/src/main/java/org/apache/bcel/classfile/InnerClass.java @@ -209,7 +209,7 @@ public final class InnerClass implements Cloneable, Node { public InnerClass copy() { try { return (InnerClass) clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { // TODO should this throw? } return null; diff --git a/src/main/java/org/apache/bcel/classfile/InnerClasses.java b/src/main/java/org/apache/bcel/classfile/InnerClasses.java index 7f98ed31..5d77f416 100644 --- a/src/main/java/org/apache/bcel/classfile/InnerClasses.java +++ b/src/main/java/org/apache/bcel/classfile/InnerClasses.java @@ -71,7 +71,7 @@ public final class InnerClasses extends Attribute { InnerClasses(final int name_index, final int length, final DataInput input, final ConstantPool constant_pool) throws IOException { this(name_index, length, (InnerClass[]) null, constant_pool); - int number_of_classes = input.readUnsignedShort(); + final int number_of_classes = input.readUnsignedShort(); inner_classes = new InnerClass[number_of_classes]; for (int i = 0; i < number_of_classes; i++) { inner_classes[i] = new InnerClass(input); @@ -102,7 +102,7 @@ public final class InnerClasses extends Attribute { public final void dump( final DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(inner_classes.length); - for (InnerClass inner_class : inner_classes) { + for (final InnerClass inner_class : inner_classes) { inner_class.dump(file); } } @@ -129,11 +129,11 @@ public final class InnerClasses extends Attribute { */ @Override public final String toString() { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); buf.append("InnerClasses("); buf.append(inner_classes.length); buf.append("):\n"); - for (InnerClass inner_class : inner_classes) { + for (final InnerClass inner_class : inner_classes) { buf.append(inner_class.toString(super.getConstantPool())).append("\n"); } return buf.toString(); @@ -146,7 +146,7 @@ public final class InnerClasses extends Attribute { @Override public Attribute copy( final ConstantPool _constant_pool ) { // TODO this could be recoded to use a lower level constructor after creating a copy of the inner classes - InnerClasses c = (InnerClasses) clone(); + final InnerClasses c = (InnerClasses) clone(); c.inner_classes = new InnerClass[inner_classes.length]; for (int i = 0; i < inner_classes.length; i++) { c.inner_classes[i] = inner_classes[i].copy(); diff --git a/src/main/java/org/apache/bcel/classfile/JavaClass.java b/src/main/java/org/apache/bcel/classfile/JavaClass.java index 857b8357..8002a417 100644 --- a/src/main/java/org/apache/bcel/classfile/JavaClass.java +++ b/src/main/java/org/apache/bcel/classfile/JavaClass.java @@ -77,15 +77,15 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl @Override public boolean equals( final Object o1, final Object o2 ) { - JavaClass THIS = (JavaClass) o1; - JavaClass THAT = (JavaClass) o2; + final JavaClass THIS = (JavaClass) o1; + final JavaClass THAT = (JavaClass) o2; return THIS.getClassName().equals(THAT.getClassName()); } @Override public int hashCode( final Object o ) { - JavaClass THIS = (JavaClass) o; + final JavaClass THIS = (JavaClass) o; return THIS.getClassName().hashCode(); } }; @@ -144,7 +144,7 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl this.attributes = attributes; this.source = source; // Get source file name if available - for (Attribute attribute : attributes) { + for (final Attribute attribute : attributes) { if (attribute instanceof SourceFile) { source_file_name = ((SourceFile) attribute).getSourceFileName(); break; @@ -156,7 +156,7 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl */ class_name = constant_pool.getConstantString(class_name_index, Const.CONSTANT_Class); class_name = Utility.compactClassName(class_name, false); - int index = class_name.lastIndexOf('.'); + final int index = class_name.lastIndexOf('.'); if (index < 0) { package_name = ""; } else { @@ -172,7 +172,7 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl } interface_names = new String[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { - String str = constant_pool.getConstantString(interfaces[i], Const.CONSTANT_Class); + final String str = constant_pool.getConstantString(interfaces[i], Const.CONSTANT_Class); interface_names[i] = Utility.compactClassName(str, false); } } @@ -230,9 +230,9 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl * @throws IOException */ public void dump(final File file) throws IOException { - String parent = file.getParent(); + final String parent = file.getParent(); if (parent != null) { - File dir = new File(parent); + final File dir = new File(parent); if (!dir.mkdirs()) { // either was not created or already existed if (!dir.isDirectory()) { throw new IOException("Could not create the directory " + dir); @@ -260,16 +260,16 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl * @return class in binary format */ public byte[] getBytes() { - ByteArrayOutputStream s = new ByteArrayOutputStream(); - DataOutputStream ds = new DataOutputStream(s); + final ByteArrayOutputStream s = new ByteArrayOutputStream(); + final DataOutputStream ds = new DataOutputStream(s); try { dump(ds); - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); } finally { try { ds.close(); - } catch (IOException e2) { + } catch (final IOException e2) { e2.printStackTrace(); } } @@ -303,20 +303,20 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl file.writeShort(class_name_index); file.writeShort(superclass_name_index); file.writeShort(interfaces.length); - for (int interface1 : interfaces) { + for (final int interface1 : interfaces) { file.writeShort(interface1); } file.writeShort(fields.length); - for (Field field : fields) { + for (final Field field : fields) { field.dump(file); } file.writeShort(methods.length); - for (Method method : methods) { + for (final Method method : methods) { method.dump(file); } if (attributes != null) { file.writeShort(attributes.length); - for (Attribute attribute : attributes) { + for (final Attribute attribute : attributes) { attribute.dump(file); } } else { @@ -432,7 +432,7 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl * java.lang.reflect.Method if any */ public Method getMethod( final java.lang.reflect.Method m ) { - for (Method method : methods) { + for (final Method method : methods) { if (m.getName().equals(method.getName()) && (m.getModifiers() == method.getModifiers()) && Type.getSignature(m).equals(method.getSignature())) { return method; @@ -596,11 +596,11 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl public String toString() { String access = Utility.accessToString(super.getAccessFlags(), true); access = access.isEmpty() ? "" : (access + " "); - StringBuilder buf = new StringBuilder(128); + final StringBuilder buf = new StringBuilder(128); buf.append(access).append(Utility.classOrInterface(super.getAccessFlags())).append(" ").append( class_name).append(" extends ").append( Utility.compactClassName(superclass_name, false)).append('\n'); - int size = interfaces.length; + final int size = interfaces.length; if (size > 0) { buf.append("implements\t\t"); for (int i = 0; i < size; i++) { @@ -619,26 +619,26 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl buf.append("ACC_SUPER flag\t\t").append(isSuper()).append("\n"); if (attributes.length > 0) { buf.append("\nAttribute(s):\n"); - for (Attribute attribute : attributes) { + for (final Attribute attribute : attributes) { buf.append(indent(attribute)); } } - AnnotationEntry[] annotations = getAnnotationEntries(); + final AnnotationEntry[] annotations = getAnnotationEntries(); if (annotations!=null && annotations.length>0) { buf.append("\nAnnotation(s):\n"); - for (AnnotationEntry annotation : annotations) { + for (final AnnotationEntry annotation : annotations) { buf.append(indent(annotation)); } } if (fields.length > 0) { buf.append("\n").append(fields.length).append(" fields:\n"); - for (Field field : fields) { + for (final Field field : fields) { buf.append("\t").append(field).append('\n'); } } if (methods.length > 0) { buf.append("\n").append(methods.length).append(" methods:\n"); - for (Method method : methods) { + for (final Method method : methods) { buf.append("\t").append(method).append('\n'); } } @@ -647,8 +647,8 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl private static String indent( final Object obj ) { - StringTokenizer tok = new StringTokenizer(obj.toString(), "\n"); - StringBuilder buf = new StringBuilder(); + final StringTokenizer tok = new StringTokenizer(obj.toString(), "\n"); + final StringBuilder buf = new StringBuilder(); while (tok.hasMoreTokens()) { buf.append("\t").append(tok.nextToken()).append("\n"); } @@ -678,7 +678,7 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl for (int i = 0; i < attributes.length; i++) { c.attributes[i] = attributes[i].copy(c.constant_pool); } - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { // TODO should this throw? } return c; @@ -714,10 +714,10 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl if (computedNestedTypeStatus) { return; } - for (Attribute attribute : this.attributes) { + for (final Attribute attribute : this.attributes) { if (attribute instanceof InnerClasses) { - InnerClass[] innerClasses = ((InnerClasses) attribute).getInnerClasses(); - for (InnerClass innerClasse : innerClasses) { + final InnerClass[] innerClasses = ((InnerClasses) attribute).getInnerClasses(); + for (final InnerClass innerClasse : innerClasses) { boolean innerClassAttributeRefersToMe = false; String inner_class_name = constant_pool.getConstantString(innerClasse.getInnerClassIndex(), Const.CONSTANT_Class); @@ -774,8 +774,8 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl if (this.equals(super_class)) { return true; } - JavaClass[] super_classes = getSuperClasses(); - for (JavaClass super_classe : super_classes) { + final JavaClass[] super_classes = getSuperClasses(); + for (final JavaClass super_classe : super_classes) { if (super_classe.equals(super_class)) { return true; } @@ -799,8 +799,8 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl if (this.equals(inter)) { return true; } - JavaClass[] super_interfaces = getAllInterfaces(); - for (JavaClass super_interface : super_interfaces) { + final JavaClass[] super_interfaces = getAllInterfaces(); + for (final JavaClass super_interface : super_interfaces) { if (super_interface.equals(inter)) { return true; } @@ -829,7 +829,7 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl */ public JavaClass[] getSuperClasses() throws ClassNotFoundException { JavaClass clazz = this; - List<JavaClass> allSuperClasses = new ArrayList<>(); + final List<JavaClass> allSuperClasses = new ArrayList<>(); for (clazz = clazz.getSuperClass(); clazz != null; clazz = clazz.getSuperClass()) { allSuperClasses.add(clazz); } @@ -841,8 +841,8 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl * Get interfaces directly implemented by this JavaClass. */ public JavaClass[] getInterfaces() throws ClassNotFoundException { - String[] _interfaces = getInterfaceNames(); - JavaClass[] classes = new JavaClass[_interfaces.length]; + final String[] _interfaces = getInterfaceNames(); + final JavaClass[] classes = new JavaClass[_interfaces.length]; for (int i = 0; i < _interfaces.length; i++) { classes[i] = repository.loadClass(_interfaces[i]); } @@ -854,13 +854,13 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl * Get all interfaces implemented by this JavaClass (transitively). */ public JavaClass[] getAllInterfaces() throws ClassNotFoundException { - ClassQueue queue = new ClassQueue(); - Set<JavaClass> allInterfaces = new TreeSet<>(); + final ClassQueue queue = new ClassQueue(); + final Set<JavaClass> allInterfaces = new TreeSet<>(); queue.enqueue(this); while (!queue.empty()) { - JavaClass clazz = queue.dequeue(); - JavaClass souper = clazz.getSuperClass(); - JavaClass[] _interfaces = clazz.getInterfaces(); + final JavaClass clazz = queue.dequeue(); + final JavaClass souper = clazz.getSuperClass(); + final JavaClass[] _interfaces = clazz.getInterfaces(); if (clazz.isInterface()) { allInterfaces.add(clazz); } else { @@ -868,7 +868,7 @@ public class JavaClass extends AccessFlags implements Cloneable, Node, Comparabl queue.enqueue(souper); } } - for (JavaClass _interface : _interfaces) { + for (final JavaClass _interface : _interfaces) { queue.enqueue(_interface); } } diff --git a/src/main/java/org/apache/bcel/classfile/LineNumber.java b/src/main/java/org/apache/bcel/classfile/LineNumber.java index ac65b35f..91627a64 100644 --- a/src/main/java/org/apache/bcel/classfile/LineNumber.java +++ b/src/main/java/org/apache/bcel/classfile/LineNumber.java @@ -140,7 +140,7 @@ public final class LineNumber implements Cloneable, Node { public LineNumber copy() { try { return (LineNumber) clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { // TODO should this throw? } return null; diff --git a/src/main/java/org/apache/bcel/classfile/LineNumberTable.java b/src/main/java/org/apache/bcel/classfile/LineNumberTable.java index a94a5dfc..69b1d209 100644 --- a/src/main/java/org/apache/bcel/classfile/LineNumberTable.java +++ b/src/main/java/org/apache/bcel/classfile/LineNumberTable.java @@ -71,7 +71,7 @@ public final class LineNumberTable extends Attribute { LineNumberTable(final int name_index, final int length, final DataInput input, final ConstantPool constant_pool) throws IOException { this(name_index, length, (LineNumber[]) null, constant_pool); - int line_number_table_length = input.readUnsignedShort(); + final int line_number_table_length = input.readUnsignedShort(); line_number_table = new LineNumber[line_number_table_length]; for (int i = 0; i < line_number_table_length; i++) { line_number_table[i] = new LineNumber(input); @@ -102,7 +102,7 @@ public final class LineNumberTable extends Attribute { public final void dump( final DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(line_number_table.length); - for (LineNumber lineNumber : line_number_table) { + for (final LineNumber lineNumber : line_number_table) { lineNumber.dump(file); } } @@ -129,9 +129,9 @@ public final class LineNumberTable extends Attribute { */ @Override public final String toString() { - StringBuilder buf = new StringBuilder(); - StringBuilder line = new StringBuilder(); - String newLine = System.getProperty("line.separator", "\n"); + final StringBuilder buf = new StringBuilder(); + final StringBuilder line = new StringBuilder(); + final String newLine = System.getProperty("line.separator", "\n"); for (int i = 0; i < line_number_table.length; i++) { line.append(line_number_table[i].toString()); if (i < line_number_table.length - 1) { @@ -165,8 +165,8 @@ public final class LineNumberTable extends Attribute { /* Do a binary search since the array is ordered. */ do { - int i = (l + r) / 2; - int j = line_number_table[i].getStartPC(); + final int i = (l + r) / 2; + final int j = line_number_table[i].getStartPC(); if (j == pos) { return line_number_table[i].getLineNumber(); } else if (pos < j) { @@ -200,7 +200,7 @@ public final class LineNumberTable extends Attribute { public Attribute copy( final ConstantPool _constant_pool ) { // TODO could use the lower level constructor and thereby allow // line_number_table to be made final - LineNumberTable c = (LineNumberTable) clone(); + final LineNumberTable c = (LineNumberTable) clone(); c.line_number_table = new LineNumber[line_number_table.length]; for (int i = 0; i < line_number_table.length; i++) { c.line_number_table[i] = line_number_table[i].copy(); diff --git a/src/main/java/org/apache/bcel/classfile/LocalVariable.java b/src/main/java/org/apache/bcel/classfile/LocalVariable.java index a92bc100..2594a235 100644 --- a/src/main/java/org/apache/bcel/classfile/LocalVariable.java +++ b/src/main/java/org/apache/bcel/classfile/LocalVariable.java @@ -183,9 +183,9 @@ public final class LocalVariable implements Cloneable, Node, Constants { * Helper method shared with LocalVariableTypeTable */ final String toStringShared( final boolean typeTable ) { - String name = getName(); - String signature = Utility.signatureToString(getSignature(), false); - String label = "LocalVariable" + (typeTable ? "Types" : "" ); + final String name = getName(); + final String signature = Utility.signatureToString(getSignature(), false); + final String label = "LocalVariable" + (typeTable ? "Types" : "" ); return label + "(start_pc = " + start_pc + ", length = " + length + ", index = " + index + ":" + signature + " " + name + ")"; } @@ -254,7 +254,7 @@ public final class LocalVariable implements Cloneable, Node, Constants { public LocalVariable copy() { try { return (LocalVariable) clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { // TODO should this throw? } return null; diff --git a/src/main/java/org/apache/bcel/classfile/LocalVariableTable.java b/src/main/java/org/apache/bcel/classfile/LocalVariableTable.java index 446f2a2d..b5a474b5 100644 --- a/src/main/java/org/apache/bcel/classfile/LocalVariableTable.java +++ b/src/main/java/org/apache/bcel/classfile/LocalVariableTable.java @@ -69,7 +69,7 @@ public class LocalVariableTable extends Attribute { LocalVariableTable(final int name_index, final int length, final DataInput input, final ConstantPool constant_pool) throws IOException { this(name_index, length, (LocalVariable[]) null, constant_pool); - int local_variable_table_length = input.readUnsignedShort(); + final int local_variable_table_length = input.readUnsignedShort(); local_variable_table = new LocalVariable[local_variable_table_length]; for (int i = 0; i < local_variable_table_length; i++) { local_variable_table[i] = new LocalVariable(input, constant_pool); @@ -100,7 +100,7 @@ public class LocalVariableTable extends Attribute { public final void dump( final DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(local_variable_table.length); - for (LocalVariable variable : local_variable_table) { + for (final LocalVariable variable : local_variable_table) { variable.dump(file); } } @@ -125,7 +125,7 @@ public class LocalVariableTable extends Attribute { */ @java.lang.Deprecated public final LocalVariable getLocalVariable( final int index ) { - for (LocalVariable variable : local_variable_table) { + for (final LocalVariable variable : local_variable_table) { if (variable.getIndex() == index) { return variable; } @@ -142,10 +142,10 @@ public class LocalVariableTable extends Attribute { * @return the LocalVariable that matches or null if not found */ public final LocalVariable getLocalVariable( final int index, final int pc ) { - for (LocalVariable variable : local_variable_table) { + for (final LocalVariable variable : local_variable_table) { if (variable.getIndex() == index) { - int start_pc = variable.getStartPC(); - int end_pc = start_pc + variable.getLength(); + final int start_pc = variable.getStartPC(); + final int end_pc = start_pc + variable.getLength(); if ((pc >= start_pc) && (pc <= end_pc)) { return variable; } @@ -165,7 +165,7 @@ public class LocalVariableTable extends Attribute { */ @Override public final String toString() { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); for (int i = 0; i < local_variable_table.length; i++) { buf.append(local_variable_table[i]); if (i < local_variable_table.length - 1) { @@ -181,7 +181,7 @@ public class LocalVariableTable extends Attribute { */ @Override public Attribute copy( final ConstantPool _constant_pool ) { - LocalVariableTable c = (LocalVariableTable) clone(); + final LocalVariableTable c = (LocalVariableTable) clone(); c.local_variable_table = new LocalVariable[local_variable_table.length]; for (int i = 0; i < local_variable_table.length; i++) { c.local_variable_table[i] = local_variable_table[i].copy(); diff --git a/src/main/java/org/apache/bcel/classfile/LocalVariableTypeTable.java b/src/main/java/org/apache/bcel/classfile/LocalVariableTypeTable.java index 3f823d7a..a969efd9 100644 --- a/src/main/java/org/apache/bcel/classfile/LocalVariableTypeTable.java +++ b/src/main/java/org/apache/bcel/classfile/LocalVariableTypeTable.java @@ -70,7 +70,7 @@ public class LocalVariableTypeTable extends Attribute { LocalVariableTypeTable(final int nameIdx, final int len, final DataInput input, final ConstantPool cpool) throws IOException { this(nameIdx, len, (LocalVariable[]) null, cpool); - int local_variable_type_table_length = input.readUnsignedShort(); + final int local_variable_type_table_length = input.readUnsignedShort(); local_variable_type_table = new LocalVariable[local_variable_type_table_length]; for (int i = 0; i < local_variable_type_table_length; i++) { @@ -87,7 +87,7 @@ public class LocalVariableTypeTable extends Attribute { public final void dump(final DataOutputStream file) throws IOException { super.dump(file); file.writeShort(local_variable_type_table.length); - for (LocalVariable variable : local_variable_type_table) { + for (final LocalVariable variable : local_variable_type_table) { variable.dump(file); } } @@ -97,7 +97,7 @@ public class LocalVariableTypeTable extends Attribute { } public final LocalVariable getLocalVariable(final int index) { - for (LocalVariable variable : local_variable_type_table) { + for (final LocalVariable variable : local_variable_type_table) { if (variable.getIndex() == index) { return variable; } @@ -115,7 +115,7 @@ public class LocalVariableTypeTable extends Attribute { */ @Override public final String toString() { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); for (int i = 0; i < local_variable_type_table.length; i++) { buf.append(local_variable_type_table[i].toStringShared(true)); @@ -133,7 +133,7 @@ public class LocalVariableTypeTable extends Attribute { */ @Override public Attribute copy(final ConstantPool constant_pool) { - LocalVariableTypeTable c = (LocalVariableTypeTable) clone(); + final LocalVariableTypeTable c = (LocalVariableTypeTable) clone(); c.local_variable_type_table = new LocalVariable[local_variable_type_table.length]; for (int i = 0; i < local_variable_type_table.length; i++) { diff --git a/src/main/java/org/apache/bcel/classfile/Method.java b/src/main/java/org/apache/bcel/classfile/Method.java index f370815a..d371c866 100644 --- a/src/main/java/org/apache/bcel/classfile/Method.java +++ b/src/main/java/org/apache/bcel/classfile/Method.java @@ -37,8 +37,8 @@ public final class Method extends FieldOrMethod { @Override public boolean equals( final Object o1, final Object o2 ) { - Method THIS = (Method) o1; - Method THAT = (Method) o2; + final Method THIS = (Method) o1; + final Method THAT = (Method) o2; return THIS.getName().equals(THAT.getName()) && THIS.getSignature().equals(THAT.getSignature()); } @@ -46,7 +46,7 @@ public final class Method extends FieldOrMethod { @Override public int hashCode( final Object o ) { - Method THIS = (Method) o; + final Method THIS = (Method) o; return THIS.getSignature().hashCode() ^ THIS.getName().hashCode(); } }; @@ -113,7 +113,7 @@ public final class Method extends FieldOrMethod { * @return Code attribute of method, if any */ public final Code getCode() { - for (Attribute attribute : super.getAttributes()) { + for (final Attribute attribute : super.getAttributes()) { if (attribute instanceof Code) { return (Code) attribute; } @@ -127,7 +127,7 @@ public final class Method extends FieldOrMethod { * exceptions the method may throw not exception handlers! */ public final ExceptionTable getExceptionTable() { - for (Attribute attribute : super.getAttributes()) { + for (final Attribute attribute : super.getAttributes()) { if (attribute instanceof ExceptionTable) { return (ExceptionTable) attribute; } @@ -140,7 +140,7 @@ public final class Method extends FieldOrMethod { * to the Code atribute. */ public final LocalVariableTable getLocalVariableTable() { - Code code = getCode(); + final Code code = getCode(); if (code == null) { return null; } @@ -152,7 +152,7 @@ public final class Method extends FieldOrMethod { * to the Code atribute. */ public final LineNumberTable getLineNumberTable() { - Code code = getCode(); + final Code code = getCode(); if (code == null) { return null; } @@ -168,23 +168,23 @@ public final class Method extends FieldOrMethod { */ @Override public final String toString() { - String access = Utility.accessToString(super.getAccessFlags()); + final String access = Utility.accessToString(super.getAccessFlags()); // Get name and signature from constant pool ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(super.getSignatureIndex(), Const.CONSTANT_Utf8); String signature = c.getBytes(); c = (ConstantUtf8) super.getConstantPool().getConstant(super.getNameIndex(), Const.CONSTANT_Utf8); - String name = c.getBytes(); + final String name = c.getBytes(); signature = Utility.methodSignatureToString(signature, name, access, true, getLocalVariableTable()); - StringBuilder buf = new StringBuilder(signature); - for (Attribute attribute : super.getAttributes()) { + final StringBuilder buf = new StringBuilder(signature); + for (final Attribute attribute : super.getAttributes()) { if (!((attribute instanceof Code) || (attribute instanceof ExceptionTable))) { buf.append(" [").append(attribute).append("]"); } } - ExceptionTable e = getExceptionTable(); + final ExceptionTable e = getExceptionTable(); if (e != null) { - String str = e.toString(); + final String str = e.toString(); if (!str.isEmpty()) { buf.append("\n\t\tthrows ").append(str); } diff --git a/src/main/java/org/apache/bcel/classfile/MethodParameter.java b/src/main/java/org/apache/bcel/classfile/MethodParameter.java index fac9b6b3..63a1a7ed 100644 --- a/src/main/java/org/apache/bcel/classfile/MethodParameter.java +++ b/src/main/java/org/apache/bcel/classfile/MethodParameter.java @@ -108,7 +108,7 @@ public class MethodParameter implements Cloneable { public MethodParameter copy() { try { return (MethodParameter) clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { // TODO should this throw? } return null; diff --git a/src/main/java/org/apache/bcel/classfile/MethodParameters.java b/src/main/java/org/apache/bcel/classfile/MethodParameters.java index abb1420f..b6e22795 100644 --- a/src/main/java/org/apache/bcel/classfile/MethodParameters.java +++ b/src/main/java/org/apache/bcel/classfile/MethodParameters.java @@ -37,7 +37,7 @@ public class MethodParameters extends Attribute { MethodParameters(final int name_index, final int length, final DataInput input, final ConstantPool constant_pool) throws IOException { super(Const.ATTR_METHOD_PARAMETERS, name_index, length, constant_pool); - int parameters_count = input.readUnsignedByte(); + final int parameters_count = input.readUnsignedByte(); parameters = new MethodParameter[parameters_count]; for (int i = 0; i < parameters_count; i++) { parameters[i] = new MethodParameter(input); @@ -59,7 +59,7 @@ public class MethodParameters extends Attribute { @Override public Attribute copy(final ConstantPool _constant_pool) { - MethodParameters c = (MethodParameters) clone(); + final MethodParameters c = (MethodParameters) clone(); c.parameters = new MethodParameter[parameters.length]; for (int i = 0; i < parameters.length; i++) { @@ -79,7 +79,7 @@ public class MethodParameters extends Attribute { public void dump(final DataOutputStream file) throws IOException { super.dump(file); file.writeByte(parameters.length); - for (MethodParameter parameter : parameters) { + for (final MethodParameter parameter : parameters) { parameter.dump(file); } } diff --git a/src/main/java/org/apache/bcel/classfile/PMGClass.java b/src/main/java/org/apache/bcel/classfile/PMGClass.java index 58ba9bff..e6c08064 100644 --- a/src/main/java/org/apache/bcel/classfile/PMGClass.java +++ b/src/main/java/org/apache/bcel/classfile/PMGClass.java @@ -138,7 +138,7 @@ public final class PMGClass extends Attribute { * @return PMG name. */ public final String getPMGName() { - ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(pmg_index, + final ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(pmg_index, Const.CONSTANT_Utf8); return c.getBytes(); } @@ -148,7 +148,7 @@ public final class PMGClass extends Attribute { * @return PMG class name. */ public final String getPMGClassName() { - ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(pmg_class_index, + final ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(pmg_class_index, Const.CONSTANT_Utf8); return c.getBytes(); } diff --git a/src/main/java/org/apache/bcel/classfile/ParameterAnnotationEntry.java b/src/main/java/org/apache/bcel/classfile/ParameterAnnotationEntry.java index 743063c9..8a8bf247 100644 --- a/src/main/java/org/apache/bcel/classfile/ParameterAnnotationEntry.java +++ b/src/main/java/org/apache/bcel/classfile/ParameterAnnotationEntry.java @@ -42,7 +42,7 @@ public class ParameterAnnotationEntry implements Node { * @throws IOException */ ParameterAnnotationEntry(final DataInput input, final ConstantPool constant_pool) throws IOException { - int annotation_table_length = input.readUnsignedShort(); + final int annotation_table_length = input.readUnsignedShort(); annotation_table = new AnnotationEntry[annotation_table_length]; for (int i = 0; i < annotation_table_length; i++) { // TODO isRuntimeVisible @@ -72,17 +72,17 @@ public class ParameterAnnotationEntry implements Node { public void dump(final DataOutputStream dos) throws IOException { dos.writeShort(annotation_table.length); - for (AnnotationEntry entry : annotation_table) { + for (final AnnotationEntry entry : annotation_table) { entry.dump(dos); } } public static ParameterAnnotationEntry[] createParameterAnnotationEntries(final Attribute[] attrs) { // Find attributes that contain parameter annotation data - List<ParameterAnnotationEntry> accumulatedAnnotations = new ArrayList<>(attrs.length); - for (Attribute attribute : attrs) { + final List<ParameterAnnotationEntry> accumulatedAnnotations = new ArrayList<>(attrs.length); + for (final Attribute attribute : attrs) { if (attribute instanceof ParameterAnnotations) { - ParameterAnnotations runtimeAnnotations = (ParameterAnnotations)attribute; + final ParameterAnnotations runtimeAnnotations = (ParameterAnnotations)attribute; Collections.addAll(accumulatedAnnotations, runtimeAnnotations.getParameterAnnotationEntries()); } } diff --git a/src/main/java/org/apache/bcel/classfile/ParameterAnnotations.java b/src/main/java/org/apache/bcel/classfile/ParameterAnnotations.java index ff9cfeef..09ceb672 100644 --- a/src/main/java/org/apache/bcel/classfile/ParameterAnnotations.java +++ b/src/main/java/org/apache/bcel/classfile/ParameterAnnotations.java @@ -43,7 +43,7 @@ public abstract class ParameterAnnotations extends Attribute { final DataInput input, final ConstantPool constant_pool) throws IOException { this(parameter_annotation_type, name_index, length, (ParameterAnnotationEntry[]) null, constant_pool); - int num_parameters = input.readUnsignedByte(); + final int num_parameters = input.readUnsignedByte(); parameter_annotation_table = new ParameterAnnotationEntry[num_parameters]; for (int i = 0; i < num_parameters; i++) { parameter_annotation_table[i] = new ParameterAnnotationEntry(input, constant_pool); @@ -107,7 +107,7 @@ public abstract class ParameterAnnotations extends Attribute { super.dump(dos); dos.writeByte(parameter_annotation_table.length); - for (ParameterAnnotationEntry element : parameter_annotation_table) { + for (final ParameterAnnotationEntry element : parameter_annotation_table) { element.dump(dos); } diff --git a/src/main/java/org/apache/bcel/classfile/Signature.java b/src/main/java/org/apache/bcel/classfile/Signature.java index 7b605b27..785a5200 100644 --- a/src/main/java/org/apache/bcel/classfile/Signature.java +++ b/src/main/java/org/apache/bcel/classfile/Signature.java @@ -118,7 +118,7 @@ public final class Signature extends Attribute { * @return GJ signature. */ public final String getSignature() { - ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(signature_index, + final ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(signature_index, Const.CONSTANT_Utf8); return c.getBytes(); } @@ -159,7 +159,7 @@ public final class Signature extends Attribute { } //System.out.println("return from ident:" + (char)ch); if (!identStart(ch)) { - StringBuilder buf2 = new StringBuilder(); + final StringBuilder buf2 = new StringBuilder(); int count = 1; while (Character.isJavaIdentifierPart((char) ch)) { buf2.append((char) ch); @@ -179,7 +179,7 @@ public final class Signature extends Attribute { } return; } - StringBuilder buf2 = new StringBuilder(); + final StringBuilder buf2 = new StringBuilder(); ch = in.read(); do { buf2.append((char) ch); @@ -232,7 +232,7 @@ public final class Signature extends Attribute { public static String translate( final String s ) { //System.out.println("Sig:" + s); - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); matchGJIdent(new MyByteArrayInputStream(s), buf); return buf.toString(); } @@ -255,7 +255,7 @@ public final class Signature extends Attribute { */ @Override public final String toString() { - String s = getSignature(); + final String s = getSignature(); return "Signature: " + s; } diff --git a/src/main/java/org/apache/bcel/classfile/SimpleElementValue.java b/src/main/java/org/apache/bcel/classfile/SimpleElementValue.java index bf3ed572..d74202f3 100644 --- a/src/main/java/org/apache/bcel/classfile/SimpleElementValue.java +++ b/src/main/java/org/apache/bcel/classfile/SimpleElementValue.java @@ -54,7 +54,7 @@ public class SimpleElementValue extends ElementValue throw new RuntimeException( "Dont call getValueString() on a non STRING ElementValue"); } - ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(getIndex(), + final ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(getIndex(), Const.CONSTANT_Utf8); return c.getBytes(); } @@ -65,7 +65,7 @@ public class SimpleElementValue extends ElementValue throw new RuntimeException( "Dont call getValueString() on a non STRING ElementValue"); } - ConstantInteger c = (ConstantInteger) super.getConstantPool().getConstant(getIndex(), + final ConstantInteger c = (ConstantInteger) super.getConstantPool().getConstant(getIndex(), Const.CONSTANT_Integer); return c.getBytes(); } @@ -76,7 +76,7 @@ public class SimpleElementValue extends ElementValue throw new RuntimeException( "Dont call getValueByte() on a non BYTE ElementValue"); } - ConstantInteger c = (ConstantInteger) super.getConstantPool().getConstant(getIndex(), + final ConstantInteger c = (ConstantInteger) super.getConstantPool().getConstant(getIndex(), Const.CONSTANT_Integer); return (byte) c.getBytes(); } @@ -87,7 +87,7 @@ public class SimpleElementValue extends ElementValue throw new RuntimeException( "Dont call getValueChar() on a non CHAR ElementValue"); } - ConstantInteger c = (ConstantInteger) super.getConstantPool().getConstant(getIndex(), + final ConstantInteger c = (ConstantInteger) super.getConstantPool().getConstant(getIndex(), Const.CONSTANT_Integer); return (char) c.getBytes(); } @@ -98,7 +98,7 @@ public class SimpleElementValue extends ElementValue throw new RuntimeException( "Dont call getValueLong() on a non LONG ElementValue"); } - ConstantLong j = (ConstantLong) super.getConstantPool().getConstant(getIndex()); + final ConstantLong j = (ConstantLong) super.getConstantPool().getConstant(getIndex()); return j.getBytes(); } @@ -108,7 +108,7 @@ public class SimpleElementValue extends ElementValue throw new RuntimeException( "Dont call getValueFloat() on a non FLOAT ElementValue"); } - ConstantFloat f = (ConstantFloat) super.getConstantPool().getConstant(getIndex()); + final ConstantFloat f = (ConstantFloat) super.getConstantPool().getConstant(getIndex()); return f.getBytes(); } @@ -118,7 +118,7 @@ public class SimpleElementValue extends ElementValue throw new RuntimeException( "Dont call getValueDouble() on a non DOUBLE ElementValue"); } - ConstantDouble d = (ConstantDouble) super.getConstantPool().getConstant(getIndex()); + final ConstantDouble d = (ConstantDouble) super.getConstantPool().getConstant(getIndex()); return d.getBytes(); } @@ -128,7 +128,7 @@ public class SimpleElementValue extends ElementValue throw new RuntimeException( "Dont call getValueBoolean() on a non BOOLEAN ElementValue"); } - ConstantInteger bo = (ConstantInteger) super.getConstantPool().getConstant(getIndex()); + final ConstantInteger bo = (ConstantInteger) super.getConstantPool().getConstant(getIndex()); return bo.getBytes() != 0; } @@ -138,7 +138,7 @@ public class SimpleElementValue extends ElementValue throw new RuntimeException( "Dont call getValueShort() on a non SHORT ElementValue"); } - ConstantInteger s = (ConstantInteger) super.getConstantPool().getConstant(getIndex()); + final ConstantInteger s = (ConstantInteger) super.getConstantPool().getConstant(getIndex()); return (short) s.getBytes(); } @@ -152,47 +152,47 @@ public class SimpleElementValue extends ElementValue @Override public String stringifyValue() { - ConstantPool cpool = super.getConstantPool(); + final ConstantPool cpool = super.getConstantPool(); final int _type = super.getType(); switch (_type) { case PRIMITIVE_INT: - ConstantInteger c = (ConstantInteger) cpool.getConstant(getIndex(), + final ConstantInteger c = (ConstantInteger) cpool.getConstant(getIndex(), Const.CONSTANT_Integer); return Integer.toString(c.getBytes()); case PRIMITIVE_LONG: - ConstantLong j = (ConstantLong) cpool.getConstant(getIndex(), + final ConstantLong j = (ConstantLong) cpool.getConstant(getIndex(), Const.CONSTANT_Long); return Long.toString(j.getBytes()); case PRIMITIVE_DOUBLE: - ConstantDouble d = (ConstantDouble) cpool.getConstant(getIndex(), + final ConstantDouble d = (ConstantDouble) cpool.getConstant(getIndex(), Const.CONSTANT_Double); return Double.toString(d.getBytes()); case PRIMITIVE_FLOAT: - ConstantFloat f = (ConstantFloat) cpool.getConstant(getIndex(), + final ConstantFloat f = (ConstantFloat) cpool.getConstant(getIndex(), Const.CONSTANT_Float); return Float.toString(f.getBytes()); case PRIMITIVE_SHORT: - ConstantInteger s = (ConstantInteger) cpool.getConstant(getIndex(), + final ConstantInteger s = (ConstantInteger) cpool.getConstant(getIndex(), Const.CONSTANT_Integer); return Integer.toString(s.getBytes()); case PRIMITIVE_BYTE: - ConstantInteger b = (ConstantInteger) cpool.getConstant(getIndex(), + final ConstantInteger b = (ConstantInteger) cpool.getConstant(getIndex(), Const.CONSTANT_Integer); return Integer.toString(b.getBytes()); case PRIMITIVE_CHAR: - ConstantInteger ch = (ConstantInteger) cpool.getConstant( + final ConstantInteger ch = (ConstantInteger) cpool.getConstant( getIndex(), Const.CONSTANT_Integer); return String.valueOf((char)ch.getBytes()); case PRIMITIVE_BOOLEAN: - ConstantInteger bo = (ConstantInteger) cpool.getConstant( + final ConstantInteger bo = (ConstantInteger) cpool.getConstant( getIndex(), Const.CONSTANT_Integer); if (bo.getBytes() == 0) { return "false"; } return "true"; case STRING: - ConstantUtf8 cu8 = (ConstantUtf8) cpool.getConstant(getIndex(), + final ConstantUtf8 cu8 = (ConstantUtf8) cpool.getConstant(getIndex(), Const.CONSTANT_Utf8); return cu8.getBytes(); default: diff --git a/src/main/java/org/apache/bcel/classfile/SourceFile.java b/src/main/java/org/apache/bcel/classfile/SourceFile.java index 5b84444f..604c918c 100644 --- a/src/main/java/org/apache/bcel/classfile/SourceFile.java +++ b/src/main/java/org/apache/bcel/classfile/SourceFile.java @@ -125,7 +125,7 @@ public final class SourceFile extends Attribute { * @return Source file name. */ public final String getSourceFileName() { - ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(sourcefile_index, + final ConstantUtf8 c = (ConstantUtf8) super.getConstantPool().getConstant(sourcefile_index, Const.CONSTANT_Utf8); return c.getBytes(); } diff --git a/src/main/java/org/apache/bcel/classfile/StackMap.java b/src/main/java/org/apache/bcel/classfile/StackMap.java index 6cdfc8f0..17f43ff8 100644 --- a/src/main/java/org/apache/bcel/classfile/StackMap.java +++ b/src/main/java/org/apache/bcel/classfile/StackMap.java @@ -65,7 +65,7 @@ public final class StackMap extends Attribute { */ StackMap(final int name_index, final int length, final DataInput input, final ConstantPool constant_pool) throws IOException { this(name_index, length, (StackMapEntry[]) null, constant_pool); - int map_length = input.readUnsignedShort(); + final int map_length = input.readUnsignedShort(); map = new StackMapEntry[map_length]; for (int i = 0; i < map_length; i++) { map[i] = new StackMapEntry(input, constant_pool); @@ -83,7 +83,7 @@ public final class StackMap extends Attribute { public final void dump( final DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(map.length); - for (StackMapEntry entry : map) { + for (final StackMapEntry entry : map) { entry.dump(file); } } @@ -103,7 +103,7 @@ public final class StackMap extends Attribute { public final void setStackMap( final StackMapEntry[] map ) { this.map = map; int len = 2; // Length of 'number_of_entries' field prior to the array of stack maps - for (StackMapEntry element : map) { + for (final StackMapEntry element : map) { len += element.getMapEntrySize(); } setLength(len); @@ -115,7 +115,7 @@ public final class StackMap extends Attribute { */ @Override public final String toString() { - StringBuilder buf = new StringBuilder("StackMap("); + final StringBuilder buf = new StringBuilder("StackMap("); for (int i = 0; i < map.length; i++) { buf.append(map[i]); if (i < map.length - 1) { @@ -132,7 +132,7 @@ public final class StackMap extends Attribute { */ @Override public Attribute copy( final ConstantPool _constant_pool ) { - StackMap c = (StackMap) clone(); + final StackMap c = (StackMap) clone(); c.map = new StackMapEntry[map.length]; for (int i = 0; i < map.length; i++) { c.map[i] = map[i].copy(); diff --git a/src/main/java/org/apache/bcel/classfile/StackMapEntry.java b/src/main/java/org/apache/bcel/classfile/StackMapEntry.java index a7a74a8e..fe850584 100644 --- a/src/main/java/org/apache/bcel/classfile/StackMapEntry.java +++ b/src/main/java/org/apache/bcel/classfile/StackMapEntry.java @@ -67,19 +67,19 @@ public final class StackMapEntry implements Node, Cloneable byte_code_offset = input.readShort(); } else if (frame_type >= Const.APPEND_FRAME && frame_type <= Const.APPEND_FRAME_MAX) { byte_code_offset = input.readShort(); - int number_of_locals = frame_type - 251; + final int number_of_locals = frame_type - 251; types_of_locals = new StackMapType[number_of_locals]; for (int i = 0; i < number_of_locals; i++) { types_of_locals[i] = new StackMapType(input, constant_pool); } } else if (frame_type == Const.FULL_FRAME) { byte_code_offset = input.readShort(); - int number_of_locals = input.readShort(); + final int number_of_locals = input.readShort(); types_of_locals = new StackMapType[number_of_locals]; for (int i = 0; i < number_of_locals; i++) { types_of_locals[i] = new StackMapType(input, constant_pool); } - int number_of_stack_items = input.readShort(); + final int number_of_stack_items = input.readShort(); types_of_stack_items = new StackMapType[number_of_stack_items]; for (int i = 0; i < number_of_stack_items; i++) { types_of_stack_items[i] = new StackMapType(input, constant_pool); @@ -154,17 +154,17 @@ public final class StackMapEntry implements Node, Cloneable file.writeShort(byte_code_offset); } else if (frame_type >= Const.APPEND_FRAME && frame_type <= Const.APPEND_FRAME_MAX) { file.writeShort(byte_code_offset); - for (StackMapType type : types_of_locals) { + for (final StackMapType type : types_of_locals) { type.dump(file); } } else if (frame_type == Const.FULL_FRAME) { file.writeShort(byte_code_offset); file.writeShort(types_of_locals.length); - for (StackMapType type : types_of_locals) { + for (final StackMapType type : types_of_locals) { type.dump(file); } file.writeShort(types_of_stack_items.length); - for (StackMapType type : types_of_stack_items) { + for (final StackMapType type : types_of_stack_items) { type.dump(file); } } else { @@ -179,7 +179,7 @@ public final class StackMapEntry implements Node, Cloneable */ @Override public final String toString() { - StringBuilder buf = new StringBuilder(64); + final StringBuilder buf = new StringBuilder(64); buf.append("("); if (frame_type >= Const.SAME_FRAME && frame_type <= Const.SAME_FRAME_MAX) { buf.append("SAME"); @@ -243,16 +243,16 @@ public final class StackMapEntry implements Node, Cloneable return 3; } else if (frame_type >= Const.APPEND_FRAME && frame_type <= Const.APPEND_FRAME_MAX) { int len = 3; - for (StackMapType types_of_local : types_of_locals) { + for (final StackMapType types_of_local : types_of_locals) { len += types_of_local.hasIndex() ? 3 : 1; } return len; } else if (frame_type == Const.FULL_FRAME) { int len = 7; - for (StackMapType types_of_local : types_of_locals) { + for (final StackMapType types_of_local : types_of_locals) { len += types_of_local.hasIndex() ? 3 : 1; } - for (StackMapType types_of_stack_item : types_of_stack_items) { + for (final StackMapType types_of_stack_item : types_of_stack_items) { len += types_of_stack_item.hasIndex() ? 3 : 1; } return len; @@ -382,7 +382,7 @@ public final class StackMapEntry implements Node, Cloneable StackMapEntry e; try { e = (StackMapEntry) clone(); - } catch (CloneNotSupportedException ex) { + } catch (final CloneNotSupportedException ex) { throw new Error("Clone Not Supported"); } diff --git a/src/main/java/org/apache/bcel/classfile/StackMapType.java b/src/main/java/org/apache/bcel/classfile/StackMapType.java index a98a88d8..71781bea 100644 --- a/src/main/java/org/apache/bcel/classfile/StackMapType.java +++ b/src/main/java/org/apache/bcel/classfile/StackMapType.java @@ -143,7 +143,7 @@ public final class StackMapType implements Cloneable { public StackMapType copy() { try { return (StackMapType) clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { // TODO should this throw? } return null; diff --git a/src/main/java/org/apache/bcel/classfile/Synthetic.java b/src/main/java/org/apache/bcel/classfile/Synthetic.java index 44bdc8a2..46f2d856 100644 --- a/src/main/java/org/apache/bcel/classfile/Synthetic.java +++ b/src/main/java/org/apache/bcel/classfile/Synthetic.java @@ -132,7 +132,7 @@ public final class Synthetic extends Attribute { */ @Override public final String toString() { - StringBuilder buf = new StringBuilder("Synthetic"); + final StringBuilder buf = new StringBuilder("Synthetic"); if (super.getLength() > 0) { buf.append(" ").append(Utility.toHexString(bytes)); } @@ -145,7 +145,7 @@ public final class Synthetic extends Attribute { */ @Override public Attribute copy( final ConstantPool _constant_pool ) { - Synthetic c = (Synthetic) clone(); + final Synthetic c = (Synthetic) clone(); if (bytes != null) { c.bytes = new byte[bytes.length]; System.arraycopy(bytes, 0, c.bytes, 0, bytes.length); diff --git a/src/main/java/org/apache/bcel/classfile/Unknown.java b/src/main/java/org/apache/bcel/classfile/Unknown.java index 22757709..958b6c05 100644 --- a/src/main/java/org/apache/bcel/classfile/Unknown.java +++ b/src/main/java/org/apache/bcel/classfile/Unknown.java @@ -48,7 +48,7 @@ public final class Unknown extends Attribute { /** @return array of unknown attributes, but just one for each kind. */ static Unknown[] getUnknownAttributes() { - Unknown[] unknowns = new Unknown[unknown_attributes.size()]; + final Unknown[] unknowns = new Unknown[unknown_attributes.size()]; unknown_attributes.values().toArray(unknowns); unknown_attributes.clear(); return unknowns; @@ -163,7 +163,7 @@ public final class Unknown extends Attribute { } String hex; if (super.getLength() > 10) { - byte[] tmp = new byte[10]; + final byte[] tmp = new byte[10]; System.arraycopy(bytes, 0, tmp, 0, 10); hex = Utility.toHexString(tmp) + "... (truncated)"; } else { @@ -178,7 +178,7 @@ public final class Unknown extends Attribute { */ @Override public Attribute copy( final ConstantPool _constant_pool ) { - Unknown c = (Unknown) clone(); + final Unknown c = (Unknown) clone(); if (bytes != null) { c.bytes = new byte[bytes.length]; System.arraycopy(bytes, 0, c.bytes, 0, bytes.length); diff --git a/src/main/java/org/apache/bcel/classfile/Utility.java b/src/main/java/org/apache/bcel/classfile/Utility.java index 7bee6dac..ab16cda8 100644 --- a/src/main/java/org/apache/bcel/classfile/Utility.java +++ b/src/main/java/org/apache/bcel/classfile/Utility.java @@ -100,7 +100,7 @@ public abstract class Utility { * @return String representation of flags */ public static String accessToString( final int access_flags, final boolean for_class ) { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); int p = 0; for (int i = 0; p < Const.MAX_ACC_FLAG; i++) { // Loop through known flags p = pow2(i); @@ -146,18 +146,18 @@ public abstract class Utility { */ public static String codeToString( final byte[] code, final ConstantPool constant_pool, final int index, final int length, final boolean verbose ) { - StringBuilder buf = new StringBuilder(code.length * 20); // Should be sufficient // CHECKSTYLE IGNORE MagicNumber + final StringBuilder buf = new StringBuilder(code.length * 20); // Should be sufficient // CHECKSTYLE IGNORE MagicNumber try (ByteSequence stream = new ByteSequence(code)) { for (int i = 0; i < index; i++) { codeToString(stream, constant_pool, verbose); } for (int i = 0; stream.available() > 0; i++) { if ((length < 0) || (i < length)) { - String indices = fillup(stream.getIndex() + ":", 6, true, ' '); + final String indices = fillup(stream.getIndex() + ":", 6, true, ' '); buf.append(indices).append(codeToString(stream, constant_pool, verbose)).append('\n'); } } - } catch (IOException e) { + } catch (final IOException e) { throw new ClassFormatException("Byte code error: " + buf.toString(), e); } return buf.toString(); @@ -182,7 +182,7 @@ public abstract class Utility { */ public static String codeToString( final ByteSequence bytes, final ConstantPool constant_pool, final boolean verbose ) throws IOException { - short opcode = (short) bytes.readUnsignedByte(); + final short opcode = (short) bytes.readUnsignedByte(); int default_offset = 0; int low; int high; @@ -194,12 +194,12 @@ public abstract class Utility { int[] jump_table; int no_pad_bytes = 0; int offset; - StringBuilder buf = new StringBuilder(Const.getOpcodeName(opcode)); + final StringBuilder buf = new StringBuilder(Const.getOpcodeName(opcode)); /* Special case: Skip (0-3) padding bytes, i.e., the * following bytes are 4-byte-aligned */ if ((opcode == Const.TABLESWITCH) || (opcode == Const.LOOKUPSWITCH)) { - int remainder = bytes.getIndex() % 4; + final int remainder = bytes.getIndex() % 4; no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder; for (int i = 0; i < no_pad_bytes; i++) { byte b; @@ -344,7 +344,7 @@ public abstract class Utility { case Const.INVOKESPECIAL: case Const.INVOKESTATIC: index = bytes.readUnsignedShort(); - Constant c = constant_pool.getConstant(index); + final Constant c = constant_pool.getConstant(index); // With Java8 operand may be either a CONSTANT_Methodref // or a CONSTANT_InterfaceMethodref. (markro) buf.append("\t").append( @@ -359,7 +359,7 @@ public abstract class Utility { break; case Const.INVOKEINTERFACE: index = bytes.readUnsignedShort(); - int nargs = bytes.readUnsignedByte(); // historical, redundant + final int nargs = bytes.readUnsignedByte(); // historical, redundant buf.append("\t").append( constant_pool .constantToString(index, Const.CONSTANT_InterfaceMethodref)) @@ -403,7 +403,7 @@ public abstract class Utility { */ case Const.MULTIANEWARRAY: { index = bytes.readUnsignedShort(); - int dimensions = bytes.readUnsignedByte(); + final int dimensions = bytes.readUnsignedByte(); buf.append("\t<").append( compactClassName(constant_pool.getConstantString(index, Const.CONSTANT_Class), false)).append(">\t").append(dimensions) @@ -477,7 +477,7 @@ public abstract class Utility { * @return Compacted class name */ public static String compactClassName( String str, final String prefix, final boolean chopit ) { - int len = prefix.length(); + final int len = prefix.length(); str = str.replace('/', '.'); // Is `/' on all systems, even DOS if (chopit) { // If string starts with `prefix' and contains no further dots @@ -516,7 +516,7 @@ public abstract class Utility { * @return `flag' with bit `i' set to 0 */ public static int clearBit( final int flag, final int i ) { - int bit = pow2(i); + final int bit = pow2(i); return (flag & bit) == 0 ? flag : flag ^ bit; } @@ -541,10 +541,10 @@ public abstract class Utility { */ public static String methodTypeToSignature( final String ret, final String[] argv ) throws ClassFormatException { - StringBuilder buf = new StringBuilder("("); + final StringBuilder buf = new StringBuilder("("); String str; if (argv != null) { - for (String element : argv) { + for (final String element : argv) { str = getSignature(element); if (str.endsWith("V")) { throw new ClassFormatException("Invalid type: " + element); @@ -577,7 +577,7 @@ public abstract class Utility { */ public static String[] methodSignatureArgumentTypes( final String signature, final boolean chopit ) throws ClassFormatException { - List<String> vec = new ArrayList<>(); + final List<String> vec = new ArrayList<>(); int index; try { // Read all declarations between for `(' and `)' if (signature.charAt(0) != '(') { @@ -589,7 +589,7 @@ public abstract class Utility { //corrected concurrent private static field acess index += unwrap(consumed_chars); // update position } - } catch (StringIndexOutOfBoundsException e) { // Should never occur + } catch (final StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); } return vec.toArray(new String[vec.size()]); @@ -619,7 +619,7 @@ public abstract class Utility { // Read return type after `)' index = signature.lastIndexOf(')') + 1; type = signatureToString(signature.substring(index), chopit); - } catch (StringIndexOutOfBoundsException e) { // Should never occur + } catch (final StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); } return type; @@ -681,7 +681,7 @@ public abstract class Utility { */ public static String methodSignatureToString( final String signature, final String name, final String access, final boolean chopit, final LocalVariableTable vars ) throws ClassFormatException { - StringBuilder buf = new StringBuilder("("); + final StringBuilder buf = new StringBuilder("("); String type; int index; int var_index = access.contains("static") ? 0 : 1; @@ -691,10 +691,10 @@ public abstract class Utility { } index = 1; // current string position while (signature.charAt(index) != ')') { - String param_type = signatureToString(signature.substring(index), chopit); + final String param_type = signatureToString(signature.substring(index), chopit); buf.append(param_type); if (vars != null) { - LocalVariable l = vars.getLocalVariable(var_index, 0); + final LocalVariable l = vars.getLocalVariable(var_index, 0); if (l != null) { buf.append(" ").append(l.getName()); } @@ -713,7 +713,7 @@ public abstract class Utility { index++; // update position // Read return type after `)' type = signatureToString(signature.substring(index), chopit); - } catch (StringIndexOutOfBoundsException e) { // Should never occur + } catch (final StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); } if (buf.length() > 1) { @@ -744,7 +744,7 @@ public abstract class Utility { int old_index; try { if (str.contains(old)) { // `old' found in str - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); old_index = 0; // String start offset // While we have something to replace while ((index = str.indexOf(old, old_index)) != -1) { @@ -755,7 +755,7 @@ public abstract class Utility { buf.append(str.substring(old_index)); // append rest of string str = buf.toString(); } - } catch (StringIndexOutOfBoundsException e) { // Should not occur + } catch (final StringIndexOutOfBoundsException e) { // Should not occur System.err.println(e); } return str; @@ -825,7 +825,7 @@ public abstract class Utility { case 'J': return "long"; case 'T': { // TypeVariableSignature - int index = signature.indexOf(';'); // Look for closing `;' + final int index = signature.indexOf(';'); // Look for closing `;' if (index < 0) { throw new ClassFormatException("Invalid signature: " + signature); } @@ -845,12 +845,12 @@ public abstract class Utility { throw new ClassFormatException("Invalid signature: " + signature); } } - int index = signature.indexOf(';', fromIndex); // Look for closing `;' + final int index = signature.indexOf(';', fromIndex); // Look for closing `;' if (index < 0) { throw new ClassFormatException("Invalid signature: " + signature); } // check to see if there are any TypeArguments - int bracketIndex = signature.substring(0, index).indexOf('<'); + final int bracketIndex = signature.substring(0, index).indexOf('<'); if (bracketIndex < 0) { // just a class identifier wrap(consumed_chars, index + 1); // "Lblabla;" `L' and `;' are removed @@ -859,7 +859,7 @@ public abstract class Utility { // we have TypeArguments; build up partial result // as we recurse for each TypeArgument - StringBuilder type = new StringBuilder(compactClassName(signature.substring(1, bracketIndex), chopit)).append("<"); + final StringBuilder type = new StringBuilder(compactClassName(signature.substring(1, bracketIndex), chopit)).append("<"); int consumed_chars = bracketIndex + 1; // Shadows global var // check for wildcards @@ -920,7 +920,7 @@ public abstract class Utility { type = signatureToString(signature.substring(n), chopit); //corrected concurrent private static field acess //Utility.consumed_chars += consumed_chars; is replaced by: - int _temp = unwrap(Utility.consumed_chars) + consumed_chars; + final int _temp = unwrap(Utility.consumed_chars) + consumed_chars; wrap(Utility.consumed_chars, _temp); return type + brackets.toString(); } @@ -929,7 +929,7 @@ public abstract class Utility { default: throw new ClassFormatException("Invalid signature: `" + signature + "'"); } - } catch (StringIndexOutOfBoundsException e) { // Should never occur + } catch (final StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid signature: " + signature, e); } } @@ -942,8 +942,8 @@ public abstract class Utility { * @return byte code signature */ public static String getSignature( String type ) { - StringBuilder buf = new StringBuilder(); - char[] chars = type.toCharArray(); + final StringBuilder buf = new StringBuilder(); + final char[] chars = type.toCharArray(); boolean char_found = false; boolean delim = false; int index = -1; @@ -995,10 +995,10 @@ public abstract class Utility { private static int countBrackets( final String brackets ) { - char[] chars = brackets.toCharArray(); + final char[] chars = brackets.toCharArray(); int count = 0; boolean open = false; - for (char c : chars) { + for (final char c : chars) { switch (c) { case '[': if (open) { @@ -1042,7 +1042,7 @@ public abstract class Utility { } index = signature.lastIndexOf(')') + 1; return typeOfSignature(signature.substring(index)); - } catch (StringIndexOutOfBoundsException e) { + } catch (final StringIndexOutOfBoundsException e) { throw new ClassFormatException("Invalid method signature: " + signature, e); } } @@ -1086,7 +1086,7 @@ public abstract class Utility { default: throw new ClassFormatException("Invalid method signature: " + signature); } - } catch (StringIndexOutOfBoundsException e) { + } catch (final StringIndexOutOfBoundsException e) { throw new ClassFormatException("Invalid method signature: " + signature, e); } } @@ -1121,10 +1121,10 @@ public abstract class Utility { * @return bytes as hexadecimal string, e.g. 00 fa 12 ... */ public static String toHexString( final byte[] bytes ) { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { - short b = byteToShort(bytes[i]); - String hex = Integer.toHexString(b); + final short b = byteToShort(bytes[i]); + final String hex = Integer.toHexString(b); if (b < 0x10) { buf.append('0'); } @@ -1162,8 +1162,8 @@ public abstract class Utility { * @return formatted string */ public static String fillup( final String str, final int length, final boolean left_justify, final char fill ) { - int len = length - str.length(); - char[] buf = new char[(len < 0) ? 0 : len]; + final int len = length - str.length(); + final char[] buf = new char[(len < 0) ? 0 : len]; for (int j = 0; j < buf.length; j++) { buf[j] = fill; } @@ -1212,7 +1212,7 @@ public abstract class Utility { if (obj == null) { return null; } - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); if (braces) { buf.append('{'); } @@ -1272,10 +1272,10 @@ public abstract class Utility { bytes = baos.toByteArray(); } } - CharArrayWriter caw = new CharArrayWriter(); + final CharArrayWriter caw = new CharArrayWriter(); try (JavaWriter jw = new JavaWriter(caw)) { - for (byte b : bytes) { - int in = b & 0x000000ff; // Normalize to unsigned + for (final byte b : bytes) { + final int in = b & 0x000000ff; // Normalize to unsigned jw.write(in); } } @@ -1302,8 +1302,8 @@ public abstract class Utility { bytes = bos.toByteArray(); } if (uncompress) { - GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes)); - byte[] tmp = new byte[bytes.length * 3]; // Rough estimate + final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes)); + final byte[] tmp = new byte[bytes.length * 3]; // Rough estimate int count = 0; int b; while ((b = gis.read()) >= 0) { @@ -1352,23 +1352,23 @@ public abstract class Utility { @Override public int read() throws IOException { - int b = in.read(); + final int b = in.read(); if (b != ESCAPE_CHAR) { return b; } - int i = in.read(); + final int i = in.read(); if (i < 0) { return -1; } if (((i >= '0') && (i <= '9')) || ((i >= 'a') && (i <= 'f'))) { // Normal escape - int j = in.read(); + final int j = in.read(); if (j < 0) { return -1; } - char[] tmp = { + final char[] tmp = { (char) i, (char) j }; - int s = Integer.parseInt(new String(tmp), 16); + final int s = Integer.parseInt(new String(tmp), 16); return s; } return MAP_CHAR[i]; @@ -1405,7 +1405,7 @@ public abstract class Utility { if (b >= 0 && b < FREE_CHARS) { out.write(CHAR_MAP[b]); } else { // Normal escape - char[] tmp = Integer.toHexString(b).toCharArray(); + final char[] tmp = Integer.toHexString(b).toCharArray(); if (tmp.length == 1) { out.write('0'); out.write(tmp[0]); @@ -1437,9 +1437,9 @@ public abstract class Utility { * Escape all occurences of newline chars '\n', quotes \", etc. */ public static String convertString( final String label ) { - char[] ch = label.toCharArray(); - StringBuilder buf = new StringBuilder(); - for (char element : ch) { + final char[] ch = label.toCharArray(); + final StringBuilder buf = new StringBuilder(); + for (final char element : ch) { switch (element) { case '\n': buf.append("\\n"); diff --git a/src/main/java/org/apache/bcel/generic/AnnotationEntryGen.java b/src/main/java/org/apache/bcel/generic/AnnotationEntryGen.java index a90a600d..016655de 100644 --- a/src/main/java/org/apache/bcel/generic/AnnotationEntryGen.java +++ b/src/main/java/org/apache/bcel/generic/AnnotationEntryGen.java @@ -69,8 +69,8 @@ public class AnnotationEntryGen { private List<ElementValuePairGen> copyValues(final ElementValuePair[] in, final ConstantPoolGen cpool, final boolean copyPoolEntries) { - List<ElementValuePairGen> out = new ArrayList<>(); - for (ElementValuePair nvp : in) { + final List<ElementValuePairGen> out = new ArrayList<>(); + for (final ElementValuePair nvp : in) { out.add(new ElementValuePairGen(nvp, cpool, copyPoolEntries)); } return out; @@ -84,9 +84,9 @@ public class AnnotationEntryGen { * Retrieve an immutable version of this AnnotationGen */ public AnnotationEntry getAnnotation() { - AnnotationEntry a = new AnnotationEntry(typeIndex, cpool.getConstantPool(), + final AnnotationEntry a = new AnnotationEntry(typeIndex, cpool.getConstantPool(), isRuntimeVisible); - for (ElementValuePairGen element : evs) { + for (final ElementValuePairGen element : evs) { a.addElementNameValuePair(element.getElementNameValuePair()); } return a; @@ -103,11 +103,11 @@ public class AnnotationEntryGen { public static AnnotationEntryGen read(final DataInput dis, final ConstantPoolGen cpool, final boolean b) throws IOException { - AnnotationEntryGen a = new AnnotationEntryGen(cpool); + final AnnotationEntryGen a = new AnnotationEntryGen(cpool); a.typeIndex = dis.readUnsignedShort(); - int elemValuePairCount = dis.readUnsignedShort(); + final int elemValuePairCount = dis.readUnsignedShort(); for (int i = 0; i < elemValuePairCount; i++) { - int nidx = dis.readUnsignedShort(); + final int nidx = dis.readUnsignedShort(); a.addElementNameValuePair(new ElementValuePairGen(nidx, ElementValueGen.readElementValue(dis, cpool), cpool)); } @@ -118,7 +118,7 @@ public class AnnotationEntryGen { public void dump(final DataOutputStream dos) throws IOException { dos.writeShort(typeIndex); // u2 index of type name in cpool dos.writeShort(evs.size()); // u2 element_value pair count - for (ElementValuePairGen envp : evs) { + for (final ElementValuePairGen envp : evs) { envp.dump(dos); } } @@ -136,7 +136,7 @@ public class AnnotationEntryGen { public final String getTypeSignature() { // ConstantClass c = (ConstantClass)cpool.getConstant(typeIndex); - ConstantUtf8 utf8 = (ConstantUtf8) cpool + final ConstantUtf8 utf8 = (ConstantUtf8) cpool .getConstant(typeIndex/* c.getNameIndex() */); return utf8.getBytes(); } @@ -155,7 +155,7 @@ public class AnnotationEntryGen { @Override public String toString() { - StringBuilder s = new StringBuilder(32); // CHECKSTYLE IGNORE MagicNumber + final StringBuilder s = new StringBuilder(32); // CHECKSTYLE IGNORE MagicNumber s.append("AnnotationGen:[").append(getTypeName()).append(" #").append(evs.size()).append(" {"); for (int i = 0; i < evs.size(); i++) { s.append(evs.get(i)); @@ -168,7 +168,7 @@ public class AnnotationEntryGen { } public String toShortString() { - StringBuilder s = new StringBuilder(); + final StringBuilder s = new StringBuilder(); s.append("@").append(getTypeName()).append("("); for (int i = 0; i < evs.size(); i++) { s.append(evs.get(i)); @@ -206,7 +206,7 @@ public class AnnotationEntryGen { int countInvisible = 0; // put the annotations in the right output stream - for (AnnotationEntryGen a : annotationEntryGens) { + for (final AnnotationEntryGen a : annotationEntryGens) { if (a.isRuntimeVisible()) { countVisible++; } else { @@ -214,8 +214,8 @@ public class AnnotationEntryGen { } } - ByteArrayOutputStream rvaBytes = new ByteArrayOutputStream(); - ByteArrayOutputStream riaBytes = new ByteArrayOutputStream(); + final ByteArrayOutputStream rvaBytes = new ByteArrayOutputStream(); + final ByteArrayOutputStream riaBytes = new ByteArrayOutputStream(); try (DataOutputStream rvaDos = new DataOutputStream(rvaBytes); DataOutputStream riaDos = new DataOutputStream(riaBytes)) { @@ -223,7 +223,7 @@ public class AnnotationEntryGen { riaDos.writeShort(countInvisible); // put the annotations in the right output stream - for (AnnotationEntryGen a : annotationEntryGens) { + for (final AnnotationEntryGen a : annotationEntryGens) { if (a.isRuntimeVisible()) { a.dump(rvaDos); } else { @@ -232,8 +232,8 @@ public class AnnotationEntryGen { } } - byte[] rvaData = rvaBytes.toByteArray(); - byte[] riaData = riaBytes.toByteArray(); + final byte[] rvaData = rvaBytes.toByteArray(); + final byte[] riaData = riaBytes.toByteArray(); int rvaIndex = -1; int riaIndex = -1; @@ -245,7 +245,7 @@ public class AnnotationEntryGen { riaIndex = cp.addUtf8("RuntimeInvisibleAnnotations"); } - List<Attribute> newAttributes = new ArrayList<>(); + final List<Attribute> newAttributes = new ArrayList<>(); if (rvaData.length > 2) { newAttributes.add( new RuntimeVisibleAnnotations(rvaIndex, rvaData.length, @@ -258,7 +258,7 @@ public class AnnotationEntryGen { } return newAttributes.toArray(new Attribute[newAttributes.size()]); - } catch (IOException e) { + } catch (final IOException e) { System.err.println("IOException whilst processing annotations"); e.printStackTrace(); } @@ -274,14 +274,14 @@ public class AnnotationEntryGen { static Attribute[] getParameterAnnotationAttributes( final ConstantPoolGen cp, final List<AnnotationEntryGen>[] /*Array of lists, array size depends on #params */vec) { - int[] visCount = new int[vec.length]; + final int[] visCount = new int[vec.length]; int totalVisCount = 0; - int[] invisCount = new int[vec.length]; + final int[] invisCount = new int[vec.length]; int totalInvisCount = 0; try { for (int i = 0; i < vec.length; i++) { if (vec[i] != null) { - for (AnnotationEntryGen element : vec[i]) { + for (final AnnotationEntryGen element : vec[i]) { if (element.isRuntimeVisible()) { visCount[i]++; totalVisCount++; @@ -293,13 +293,13 @@ public class AnnotationEntryGen { } } // Lets do the visible ones - ByteArrayOutputStream rvaBytes = new ByteArrayOutputStream(); + final ByteArrayOutputStream rvaBytes = new ByteArrayOutputStream(); try (DataOutputStream rvaDos = new DataOutputStream(rvaBytes)) { rvaDos.writeByte(vec.length); // First goes number of parameters for (int i = 0; i < vec.length; i++) { rvaDos.writeShort(visCount[i]); if (visCount[i] > 0) { - for (AnnotationEntryGen element : vec[i]) { + for (final AnnotationEntryGen element : vec[i]) { if (element.isRuntimeVisible()) { element.dump(rvaDos); } @@ -308,13 +308,13 @@ public class AnnotationEntryGen { } } // Lets do the invisible ones - ByteArrayOutputStream riaBytes = new ByteArrayOutputStream(); + final ByteArrayOutputStream riaBytes = new ByteArrayOutputStream(); try (DataOutputStream riaDos = new DataOutputStream(riaBytes)) { riaDos.writeByte(vec.length); // First goes number of parameters for (int i = 0; i < vec.length; i++) { riaDos.writeShort(invisCount[i]); if (invisCount[i] > 0) { - for (AnnotationEntryGen element : vec[i]) { + for (final AnnotationEntryGen element : vec[i]) { if (!element.isRuntimeVisible()) { element.dump(riaDos); } @@ -322,8 +322,8 @@ public class AnnotationEntryGen { } } } - byte[] rvaData = rvaBytes.toByteArray(); - byte[] riaData = riaBytes.toByteArray(); + final byte[] rvaData = rvaBytes.toByteArray(); + final byte[] riaData = riaBytes.toByteArray(); int rvaIndex = -1; int riaIndex = -1; if (totalVisCount > 0) { @@ -332,7 +332,7 @@ public class AnnotationEntryGen { if (totalInvisCount > 0) { riaIndex = cp.addUtf8("RuntimeInvisibleParameterAnnotations"); } - List<Attribute> newAttributes = new ArrayList<>(); + final List<Attribute> newAttributes = new ArrayList<>(); if (totalVisCount > 0) { newAttributes .add(new RuntimeVisibleParameterAnnotations(rvaIndex, @@ -344,7 +344,7 @@ public class AnnotationEntryGen { riaData.length, new DataInputStream(new ByteArrayInputStream(riaData)), cp.getConstantPool())); } return newAttributes.toArray(new Attribute[newAttributes.size()]); - } catch (IOException e) { + } catch (final IOException e) { System.err .println("IOException whilst processing parameter annotations"); e.printStackTrace(); diff --git a/src/main/java/org/apache/bcel/generic/ArrayElementValueGen.java b/src/main/java/org/apache/bcel/generic/ArrayElementValueGen.java index 8e123a21..240c1ddb 100644 --- a/src/main/java/org/apache/bcel/generic/ArrayElementValueGen.java +++ b/src/main/java/org/apache/bcel/generic/ArrayElementValueGen.java @@ -49,7 +49,7 @@ public class ArrayElementValueGen extends ElementValueGen "Only element values of type array can be built with this ctor - type specified: " + type); } this.evalues = new ArrayList<>(); - for (ElementValue datum : datums) { + for (final ElementValue datum : datums) { evalues.add(ElementValueGen.copy(datum, cpool, true)); } } @@ -60,9 +60,9 @@ public class ArrayElementValueGen extends ElementValueGen @Override public ElementValue getElementValue() { - ElementValue[] immutableData = new ElementValue[evalues.size()]; + final ElementValue[] immutableData = new ElementValue[evalues.size()]; int i = 0; - for (ElementValueGen element : evalues) { + for (final ElementValueGen element : evalues) { immutableData[i++] = element.getElementValue(); } return new ArrayElementValue(super.getElementValueType(), @@ -79,8 +79,8 @@ public class ArrayElementValueGen extends ElementValueGen { super(ARRAY, cpool); evalues = new ArrayList<>(); - ElementValue[] in = value.getElementValuesArray(); - for (ElementValue element : in) { + final ElementValue[] in = value.getElementValuesArray(); + for (final ElementValue element : in) { evalues.add(ElementValueGen.copy(element, cpool, copyPoolEntries)); } } @@ -90,7 +90,7 @@ public class ArrayElementValueGen extends ElementValueGen { dos.writeByte(super.getElementValueType()); // u1 type of value (ARRAY == '[') dos.writeShort(evalues.size()); - for (ElementValueGen element : evalues) { + for (final ElementValueGen element : evalues) { element.dump(dos); } } @@ -98,10 +98,10 @@ public class ArrayElementValueGen extends ElementValueGen @Override public String stringifyValue() { - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); sb.append("["); String comma = ""; - for (ElementValueGen element : evalues) { + for (final ElementValueGen element : evalues) { sb.append(comma); comma = ","; sb.append(element.stringifyValue()); diff --git a/src/main/java/org/apache/bcel/generic/ArrayType.java b/src/main/java/org/apache/bcel/generic/ArrayType.java index 96b723dd..ff35701f 100644 --- a/src/main/java/org/apache/bcel/generic/ArrayType.java +++ b/src/main/java/org/apache/bcel/generic/ArrayType.java @@ -62,7 +62,7 @@ public final class ArrayType extends ReferenceType { } switch (type.getType()) { case Const.T_ARRAY: - ArrayType array = (ArrayType) type; + final ArrayType array = (ArrayType) type; this.dimensions = dimensions + array.dimensions; basic_type = array.basic_type; break; @@ -73,7 +73,7 @@ public final class ArrayType extends ReferenceType { basic_type = type; break; } - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); for (int i = 0; i < this.dimensions; i++) { buf.append('['); } @@ -121,7 +121,7 @@ public final class ArrayType extends ReferenceType { @Override public boolean equals( final Object _type ) { if (_type instanceof ArrayType) { - ArrayType array = (ArrayType) _type; + final ArrayType array = (ArrayType) _type; return (array.dimensions == dimensions) && array.basic_type.equals(basic_type); } return false; diff --git a/src/main/java/org/apache/bcel/generic/BranchHandle.java b/src/main/java/org/apache/bcel/generic/BranchHandle.java index ba942c9d..5b75d8af 100644 --- a/src/main/java/org/apache/bcel/generic/BranchHandle.java +++ b/src/main/java/org/apache/bcel/generic/BranchHandle.java @@ -49,7 +49,7 @@ public final class BranchHandle extends InstructionHandle { if (bh_list == null) { return new BranchHandle(i); } - BranchHandle bh = bh_list; + final BranchHandle bh = bh_list; bh_list = (BranchHandle) bh.getNext(); bh.setInstruction(i); return bh; @@ -85,7 +85,7 @@ public final class BranchHandle extends InstructionHandle { @Override protected int updatePosition( final int offset, final int max_offset ) { - int x = bi.updatePosition(offset, max_offset); + final int x = bi.updatePosition(offset, max_offset); super.setPosition(bi.getPosition()); return x; } diff --git a/src/main/java/org/apache/bcel/generic/BranchInstruction.java b/src/main/java/org/apache/bcel/generic/BranchInstruction.java index d74512d4..7fc0c33a 100644 --- a/src/main/java/org/apache/bcel/generic/BranchInstruction.java +++ b/src/main/java/org/apache/bcel/generic/BranchInstruction.java @@ -93,7 +93,7 @@ public abstract class BranchInstruction extends Instruction implements Instructi throw new ClassGenException("Target of " + super.toString(true) + " is invalid null handle"); } - int t = _target.getPosition(); + final int t = _target.getPosition(); if (t < 0) { throw new ClassGenException("Invalid branch target position offset for " + super.toString(true) + ":" + t + ":" + _target); @@ -139,7 +139,7 @@ public abstract class BranchInstruction extends Instruction implements Instructi */ @Override public String toString( final boolean verbose ) { - String s = super.toString(verbose); + final String s = super.toString(verbose); String t = "null"; if (verbose) { if (target != null) { diff --git a/src/main/java/org/apache/bcel/generic/CPInstruction.java b/src/main/java/org/apache/bcel/generic/CPInstruction.java index 247d0a5f..a3f22391 100644 --- a/src/main/java/org/apache/bcel/generic/CPInstruction.java +++ b/src/main/java/org/apache/bcel/generic/CPInstruction.java @@ -93,7 +93,7 @@ public abstract class CPInstruction extends Instruction implements TypedInstruct */ @Override public String toString( final ConstantPool cp ) { - Constant c = cp.getConstant(index); + final Constant c = cp.getConstant(index); String str = cp.constantToString(c); if (c instanceof ConstantClass) { str = str.replace('.', '/'); @@ -140,7 +140,7 @@ public abstract class CPInstruction extends Instruction implements TypedInstruct */ @Override public Type getType( final ConstantPoolGen cpg ) { - ConstantPool cp = cpg.getConstantPool(); + final ConstantPool cp = cpg.getConstantPool(); String name = cp.getConstantString(index, org.apache.bcel.Const.CONSTANT_Class); if (!name.startsWith("[")) { name = "L" + name + ";"; diff --git a/src/main/java/org/apache/bcel/generic/ClassElementValueGen.java b/src/main/java/org/apache/bcel/generic/ClassElementValueGen.java index 72c46122..60f76f66 100644 --- a/src/main/java/org/apache/bcel/generic/ClassElementValueGen.java +++ b/src/main/java/org/apache/bcel/generic/ClassElementValueGen.java @@ -80,7 +80,7 @@ public class ClassElementValueGen extends ElementValueGen public String getClassString() { - ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(idx); + final ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(idx); return cu8.getBytes(); // ConstantClass c = (ConstantClass)getConstantPool().getConstant(idx); // ConstantUtf8 utf8 = diff --git a/src/main/java/org/apache/bcel/generic/ClassGen.java b/src/main/java/org/apache/bcel/generic/ClassGen.java index e9ecb385..53b0d4d2 100644 --- a/src/main/java/org/apache/bcel/generic/ClassGen.java +++ b/src/main/java/org/apache/bcel/generic/ClassGen.java @@ -64,15 +64,15 @@ public class ClassGen extends AccessFlags implements Cloneable { @Override public boolean equals( final Object o1, final Object o2 ) { - ClassGen THIS = (ClassGen) o1; - ClassGen THAT = (ClassGen) o2; + final ClassGen THIS = (ClassGen) o1; + final ClassGen THAT = (ClassGen) o2; return THIS.getClassName().equals(THAT.getClassName()); } @Override public int hashCode( final Object o ) { - ClassGen THIS = (ClassGen) o; + final ClassGen THIS = (ClassGen) o; return THIS.getClassName().hashCode(); } }; @@ -102,7 +102,7 @@ public class ClassGen extends AccessFlags implements Cloneable { class_name_index = cp.addClass(class_name); superclass_name_index = cp.addClass(super_class_name); if (interfaces != null) { - for (String interface1 : interfaces) { + for (final String interface1 : interfaces) { addInterface(interface1); } } @@ -138,27 +138,27 @@ public class ClassGen extends AccessFlags implements Cloneable { cp = new ConstantPoolGen(clazz.getConstantPool()); major = clazz.getMajor(); minor = clazz.getMinor(); - Attribute[] attributes = clazz.getAttributes(); + final Attribute[] attributes = clazz.getAttributes(); // J5TODO: Could make unpacking lazy, done on first reference - AnnotationEntryGen[] annotations = unpackAnnotations(attributes); - Method[] methods = clazz.getMethods(); - Field[] fields = clazz.getFields(); - String[] interfaces = clazz.getInterfaceNames(); - for (String interface1 : interfaces) { + final AnnotationEntryGen[] annotations = unpackAnnotations(attributes); + final Method[] methods = clazz.getMethods(); + final Field[] fields = clazz.getFields(); + final String[] interfaces = clazz.getInterfaceNames(); + for (final String interface1 : interfaces) { addInterface(interface1); } - for (Attribute attribute : attributes) { + for (final Attribute attribute : attributes) { if (!(attribute instanceof Annotations)) { addAttribute(attribute); } } - for (AnnotationEntryGen annotation : annotations) { + for (final AnnotationEntryGen annotation : annotations) { addAnnotationEntry(annotation); } - for (Method method : methods) { + for (final Method method : methods) { addMethod(method); } - for (Field field : fields) { + for (final Field field : fields) { addField(field); } } @@ -168,13 +168,13 @@ public class ClassGen extends AccessFlags implements Cloneable { */ private AnnotationEntryGen[] unpackAnnotations(final Attribute[] attrs) { - List<AnnotationEntryGen> annotationGenObjs = new ArrayList<>(); - for (Attribute attr : attrs) { + final List<AnnotationEntryGen> annotationGenObjs = new ArrayList<>(); + for (final Attribute attr : attrs) { if (attr instanceof RuntimeVisibleAnnotations) { - RuntimeVisibleAnnotations rva = (RuntimeVisibleAnnotations) attr; - AnnotationEntry[] annos = rva.getAnnotationEntries(); - for (AnnotationEntry a : annos) { + final RuntimeVisibleAnnotations rva = (RuntimeVisibleAnnotations) attr; + final AnnotationEntry[] annos = rva.getAnnotationEntries(); + for (final AnnotationEntry a : annos) { annotationGenObjs.add(new AnnotationEntryGen(a, getConstantPool(), false)); } @@ -182,9 +182,9 @@ public class ClassGen extends AccessFlags implements Cloneable { else if (attr instanceof RuntimeInvisibleAnnotations) { - RuntimeInvisibleAnnotations ria = (RuntimeInvisibleAnnotations) attr; - AnnotationEntry[] annos = ria.getAnnotationEntries(); - for (AnnotationEntry a : annos) { + final RuntimeInvisibleAnnotations ria = (RuntimeInvisibleAnnotations) attr; + final AnnotationEntry[] annos = ria.getAnnotationEntries(); + for (final AnnotationEntry a : annos) { annotationGenObjs.add(new AnnotationEntryGen(a, getConstantPool(), false)); } @@ -198,21 +198,21 @@ public class ClassGen extends AccessFlags implements Cloneable { * @return the (finally) built up Java class object. */ public JavaClass getJavaClass() { - int[] interfaces = getInterfaces(); - Field[] fields = getFields(); - Method[] methods = getMethods(); + final int[] interfaces = getInterfaces(); + final Field[] fields = getFields(); + final Method[] methods = getMethods(); Attribute[] attributes = null; if (annotation_vec.isEmpty()) { attributes = getAttributes(); } else { // TODO: Sometime later, trash any attributes called 'RuntimeVisibleAnnotations' or 'RuntimeInvisibleAnnotations' - Attribute[] annAttributes = AnnotationEntryGen.getAnnotationAttributes(cp, getAnnotationEntries()); + final Attribute[] annAttributes = AnnotationEntryGen.getAnnotationAttributes(cp, getAnnotationEntries()); attributes = new Attribute[attribute_vec.size()+annAttributes.length]; attribute_vec.toArray(attributes); System.arraycopy(annAttributes,0,attributes,attribute_vec.size(),annAttributes.length); } // Must be last since the above calls may still add something to it - ConstantPool _cp = this.cp.getFinalConstantPool(); + final ConstantPool _cp = this.cp.getFinalConstantPool(); return new JavaClass(class_name_index, superclass_name_index, file_name, major, minor, super.getAccessFlags(), _cp, interfaces, fields, methods, attributes); } @@ -296,11 +296,11 @@ public class ClassGen extends AccessFlags implements Cloneable { * @param access_flags rights for constructor */ public void addEmptyConstructor( final int access_flags ) { - InstructionList il = new InstructionList(); + final InstructionList il = new InstructionList(); il.append(InstructionConst.THIS); // Push `this' il.append(new INVOKESPECIAL(cp.addMethodref(super_class_name, "<init>", "()V"))); il.append(InstructionConst.RETURN); - MethodGen mg = new MethodGen(access_flags, Type.VOID, Type.NO_ARGS, null, "<init>", + final MethodGen mg = new MethodGen(access_flags, Type.VOID, Type.NO_ARGS, null, "<init>", class_name, il, cp); mg.setMaxStack(1); addMethod(mg.getMethod()); @@ -324,7 +324,7 @@ public class ClassGen extends AccessFlags implements Cloneable { /** @return field object with given name, or null */ public Field containsField( final String name ) { - for (Field f : field_vec) { + for (final Field f : field_vec) { if (f.getName().equals(name)) { return f; } @@ -336,7 +336,7 @@ public class ClassGen extends AccessFlags implements Cloneable { /** @return method object with given name and signature, or null */ public Method containsMethod( final String name, final String signature ) { - for (Method m : method_vec) { + for (final Method m : method_vec) { if (m.getName().equals(name) && m.getSignature().equals(signature)) { return m; } @@ -370,7 +370,7 @@ public class ClassGen extends AccessFlags implements Cloneable { if (new_ == null) { throw new ClassGenException("Replacement method must not be null"); } - int i = method_vec.indexOf(old); + final int i = method_vec.indexOf(old); if (i < 0) { method_vec.add(new_); } else { @@ -386,7 +386,7 @@ public class ClassGen extends AccessFlags implements Cloneable { if (new_ == null) { throw new ClassGenException("Replacement method must not be null"); } - int i = field_vec.indexOf(old); + final int i = field_vec.indexOf(old); if (i < 0) { field_vec.add(new_); } else { @@ -438,7 +438,7 @@ public class ClassGen extends AccessFlags implements Cloneable { public void setMethods( final Method[] methods ) { method_vec.clear(); - for (Method method : methods) { + for (final Method method : methods) { addMethod(method); } } @@ -455,16 +455,16 @@ public class ClassGen extends AccessFlags implements Cloneable { public String[] getInterfaceNames() { - int size = interface_vec.size(); - String[] interfaces = new String[size]; + final int size = interface_vec.size(); + final String[] interfaces = new String[size]; interface_vec.toArray(interfaces); return interfaces; } public int[] getInterfaces() { - int size = interface_vec.size(); - int[] interfaces = new int[size]; + final int size = interface_vec.size(); + final int[] interfaces = new int[size]; for (int i = 0; i < size; i++) { interfaces[i] = cp.addClass(interface_vec.get(i)); } @@ -548,7 +548,7 @@ public class ClassGen extends AccessFlags implements Cloneable { */ public void update() { if (observers != null) { - for (ClassObserver observer : observers) { + for (final ClassObserver observer : observers) { observer.notify(this); } } @@ -559,7 +559,7 @@ public class ClassGen extends AccessFlags implements Cloneable { public Object clone() { try { return super.clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { throw new Error("Clone Not Supported"); // never happens } } diff --git a/src/main/java/org/apache/bcel/generic/CodeExceptionGen.java b/src/main/java/org/apache/bcel/generic/CodeExceptionGen.java index d0667c6c..ada53f5d 100644 --- a/src/main/java/org/apache/bcel/generic/CodeExceptionGen.java +++ b/src/main/java/org/apache/bcel/generic/CodeExceptionGen.java @@ -180,7 +180,7 @@ public final class CodeExceptionGen implements InstructionTargeter, Cloneable { public Object clone() { try { return super.clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { throw new Error("Clone Not Supported"); // never happens } } diff --git a/src/main/java/org/apache/bcel/generic/ConstantPoolGen.java b/src/main/java/org/apache/bcel/generic/ConstantPoolGen.java index 446b8433..6267e4db 100644 --- a/src/main/java/org/apache/bcel/generic/ConstantPoolGen.java +++ b/src/main/java/org/apache/bcel/generic/ConstantPoolGen.java @@ -94,7 +94,7 @@ public class ConstantPoolGen { * @param cs array of given constants, new ones will be appended */ public ConstantPoolGen(final Constant[] cs) { - StringBuilder sb = new StringBuilder(DEFAULT_BUFFER_SIZE); + final StringBuilder sb = new StringBuilder(DEFAULT_BUFFER_SIZE); size = Math.max(DEFAULT_BUFFER_SIZE, cs.length + 64); constants = new Constant[size]; @@ -106,43 +106,43 @@ public class ConstantPoolGen { for (int i = 1; i < index; i++) { - Constant c = constants[i]; + final Constant c = constants[i]; if (c instanceof ConstantString) { - ConstantString s = (ConstantString) c; - ConstantUtf8 u8 = (ConstantUtf8) constants[s.getStringIndex()]; - String key = u8.getBytes(); + final ConstantString s = (ConstantString) c; + final ConstantUtf8 u8 = (ConstantUtf8) constants[s.getStringIndex()]; + final String key = u8.getBytes(); if (!string_table.containsKey(key)) { string_table.put(key, new Index(i)); } } else if (c instanceof ConstantClass) { - ConstantClass s = (ConstantClass) c; - ConstantUtf8 u8 = (ConstantUtf8) constants[s.getNameIndex()]; - String key = u8.getBytes(); + final ConstantClass s = (ConstantClass) c; + final ConstantUtf8 u8 = (ConstantUtf8) constants[s.getNameIndex()]; + final String key = u8.getBytes(); if (!class_table.containsKey(key)) { class_table.put(key, new Index(i)); } } else if (c instanceof ConstantNameAndType) { - ConstantNameAndType n = (ConstantNameAndType) c; - ConstantUtf8 u8 = (ConstantUtf8) constants[n.getNameIndex()]; - ConstantUtf8 u8_2 = (ConstantUtf8) constants[n.getSignatureIndex()]; + final ConstantNameAndType n = (ConstantNameAndType) c; + final ConstantUtf8 u8 = (ConstantUtf8) constants[n.getNameIndex()]; + final ConstantUtf8 u8_2 = (ConstantUtf8) constants[n.getSignatureIndex()]; sb.append(u8.getBytes()); sb.append(NAT_DELIM); sb.append(u8_2.getBytes()); - String key = sb.toString(); + final String key = sb.toString(); sb.delete(0, sb.length()); if (!n_a_t_table.containsKey(key)) { n_a_t_table.put(key, new Index(i)); } } else if (c instanceof ConstantUtf8) { - ConstantUtf8 u = (ConstantUtf8) c; - String key = u.getBytes(); + final ConstantUtf8 u = (ConstantUtf8) c; + final String key = u.getBytes(); if (!utf8_table.containsKey(key)) { utf8_table.put(key, new Index(i)); } } else if (c instanceof ConstantCP) { - ConstantCP m = (ConstantCP) c; + final ConstantCP m = (ConstantCP) c; String class_name; ConstantUtf8 u8; @@ -151,16 +151,16 @@ public class ConstantPoolGen { // since name can't begin with digit, can use // METHODREF_DELIM with out fear of duplicates. } else { - ConstantClass clazz = (ConstantClass) constants[m.getClassIndex()]; + final ConstantClass clazz = (ConstantClass) constants[m.getClassIndex()]; u8 = (ConstantUtf8) constants[clazz.getNameIndex()]; class_name = u8.getBytes().replace('/', '.'); } - ConstantNameAndType n = (ConstantNameAndType) constants[m.getNameAndTypeIndex()]; + final ConstantNameAndType n = (ConstantNameAndType) constants[m.getNameAndTypeIndex()]; u8 = (ConstantUtf8) constants[n.getNameIndex()]; - String method_name = u8.getBytes(); + final String method_name = u8.getBytes(); u8 = (ConstantUtf8) constants[n.getSignatureIndex()]; - String signature = u8.getBytes(); + final String signature = u8.getBytes(); String delim = METHODREF_DELIM; if (c instanceof ConstantInterfaceMethodref) { @@ -174,7 +174,7 @@ public class ConstantPoolGen { sb.append(method_name); sb.append(delim); sb.append(signature); - String key = sb.toString(); + final String key = sb.toString(); sb.delete(0, sb.length()); if (!cp_table.containsKey(key)) { @@ -222,7 +222,7 @@ public class ConstantPoolGen { */ protected void adjustSize() { if (index + 3 >= size) { - Constant[] cs = constants; + final Constant[] cs = constants; size *= 2; constants = new Constant[size]; System.arraycopy(cs, 0, constants, 0, index); @@ -239,7 +239,7 @@ public class ConstantPoolGen { * @return index on success, -1 otherwise */ public int lookupString( final String str ) { - Index index = string_table.get(str); + final Index index = string_table.get(str); return (index != null) ? index.index : -1; } @@ -255,9 +255,9 @@ public class ConstantPoolGen { if ((ret = lookupString(str)) != -1) { return ret; // Already in CP } - int utf8 = addUtf8(str); + final int utf8 = addUtf8(str); adjustSize(); - ConstantString s = new ConstantString(utf8); + final ConstantString s = new ConstantString(utf8); ret = index; constants[index++] = s; if (!string_table.containsKey(str)) { @@ -276,7 +276,7 @@ public class ConstantPoolGen { * @return index on success, -1 otherwise */ public int lookupClass( final String str ) { - Index index = class_table.get(str.replace('.', '/')); + final Index index = class_table.get(str.replace('.', '/')); return (index != null) ? index.index : -1; } @@ -287,7 +287,7 @@ public class ConstantPoolGen { return ret; // Already in CP } adjustSize(); - ConstantClass c = new ConstantClass(addUtf8(clazz)); + final ConstantClass c = new ConstantClass(addUtf8(clazz)); ret = index; constants[index++] = c; if (!class_table.containsKey(clazz)) { @@ -340,7 +340,7 @@ public class ConstantPoolGen { public int lookupInteger( final int n ) { for (int i = 1; i < index; i++) { if (constants[i] instanceof ConstantInteger) { - ConstantInteger c = (ConstantInteger) constants[i]; + final ConstantInteger c = (ConstantInteger) constants[i]; if (c.getBytes() == n) { return i; } @@ -375,10 +375,10 @@ public class ConstantPoolGen { * @return index on success, -1 otherwise */ public int lookupFloat( final float n ) { - int bits = Float.floatToIntBits(n); + final int bits = Float.floatToIntBits(n); for (int i = 1; i < index; i++) { if (constants[i] instanceof ConstantFloat) { - ConstantFloat c = (ConstantFloat) constants[i]; + final ConstantFloat c = (ConstantFloat) constants[i]; if (Float.floatToIntBits(c.getBytes()) == bits) { return i; } @@ -415,7 +415,7 @@ public class ConstantPoolGen { * @return index on success, -1 otherwise */ public int lookupUtf8( final String n ) { - Index index = utf8_table.get(n); + final Index index = utf8_table.get(n); return (index != null) ? index.index : -1; } @@ -450,7 +450,7 @@ public class ConstantPoolGen { public int lookupLong( final long n ) { for (int i = 1; i < index; i++) { if (constants[i] instanceof ConstantLong) { - ConstantLong c = (ConstantLong) constants[i]; + final ConstantLong c = (ConstantLong) constants[i]; if (c.getBytes() == n) { return i; } @@ -486,10 +486,10 @@ public class ConstantPoolGen { * @return index on success, -1 otherwise */ public int lookupDouble( final double n ) { - long bits = Double.doubleToLongBits(n); + final long bits = Double.doubleToLongBits(n); for (int i = 1; i < index; i++) { if (constants[i] instanceof ConstantDouble) { - ConstantDouble c = (ConstantDouble) constants[i]; + final ConstantDouble c = (ConstantDouble) constants[i]; if (Double.doubleToLongBits(c.getBytes()) == bits) { return i; } @@ -528,7 +528,7 @@ public class ConstantPoolGen { * @return index on success, -1 otherwise */ public int lookupNameAndType( final String name, final String signature ) { - Index _index = n_a_t_table.get(name + NAT_DELIM + signature); + final Index _index = n_a_t_table.get(name + NAT_DELIM + signature); return (_index != null) ? _index.index : -1; } @@ -553,7 +553,7 @@ public class ConstantPoolGen { signature_index = addUtf8(signature); ret = index; constants[index++] = new ConstantNameAndType(name_index, signature_index); - String key = name + NAT_DELIM + signature; + final String key = name + NAT_DELIM + signature; if (!n_a_t_table.containsKey(key)) { n_a_t_table.put(key, new Index(ret)); } @@ -572,7 +572,7 @@ public class ConstantPoolGen { * @return index on success, -1 otherwise */ public int lookupMethodref( final String class_name, final String method_name, final String signature ) { - Index index = cp_table.get(class_name + METHODREF_DELIM + method_name + final Index index = cp_table.get(class_name + METHODREF_DELIM + method_name + METHODREF_DELIM + signature); return (index != null) ? index.index : -1; } @@ -604,7 +604,7 @@ public class ConstantPoolGen { class_index = addClass(class_name); ret = index; constants[index++] = new ConstantMethodref(class_index, name_and_type_index); - String key = class_name + METHODREF_DELIM + method_name + METHODREF_DELIM + signature; + final String key = class_name + METHODREF_DELIM + method_name + METHODREF_DELIM + signature; if (!cp_table.containsKey(key)) { cp_table.put(key, new Index(ret)); } @@ -626,7 +626,7 @@ public class ConstantPoolGen { * @return index on success, -1 otherwise */ public int lookupInterfaceMethodref( final String class_name, final String method_name, final String signature ) { - Index index = cp_table.get(class_name + IMETHODREF_DELIM + method_name + final Index index = cp_table.get(class_name + IMETHODREF_DELIM + method_name + IMETHODREF_DELIM + signature); return (index != null) ? index.index : -1; } @@ -659,7 +659,7 @@ public class ConstantPoolGen { name_and_type_index = addNameAndType(method_name, signature); ret = index; constants[index++] = new ConstantInterfaceMethodref(class_index, name_and_type_index); - String key = class_name + IMETHODREF_DELIM + method_name + IMETHODREF_DELIM + signature; + final String key = class_name + IMETHODREF_DELIM + method_name + IMETHODREF_DELIM + signature; if (!cp_table.containsKey(key)) { cp_table.put(key, new Index(ret)); } @@ -681,7 +681,7 @@ public class ConstantPoolGen { * @return index on success, -1 otherwise */ public int lookupFieldref( final String class_name, final String field_name, final String signature ) { - Index index = cp_table.get(class_name + FIELDREF_DELIM + field_name + final Index index = cp_table.get(class_name + FIELDREF_DELIM + field_name + FIELDREF_DELIM + signature); return (index != null) ? index.index : -1; } @@ -708,7 +708,7 @@ public class ConstantPoolGen { name_and_type_index = addNameAndType(field_name, signature); ret = index; constants[index++] = new ConstantFieldref(class_index, name_and_type_index); - String key = class_name + FIELDREF_DELIM + field_name + FIELDREF_DELIM + signature; + final String key = class_name + FIELDREF_DELIM + field_name + FIELDREF_DELIM + signature; if (!cp_table.containsKey(key)) { cp_table.put(key, new Index(ret)); } @@ -756,7 +756,7 @@ public class ConstantPoolGen { * @return constant pool with proper length */ public ConstantPool getFinalConstantPool() { - Constant[] cs = new Constant[index]; + final Constant[] cs = new Constant[index]; System.arraycopy(constants, 0, cs, 0, index); return new ConstantPool(cs); } @@ -767,7 +767,7 @@ public class ConstantPoolGen { */ @Override public String toString() { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); for (int i = 1; i < index; i++) { buf.append(i).append(")").append(constants[i]).append("\n"); } @@ -778,22 +778,22 @@ public class ConstantPoolGen { /** Import constant from another ConstantPool and return new index. */ public int addConstant( final Constant c, final ConstantPoolGen cp ) { - Constant[] constants = cp.getConstantPool().getConstantPool(); + final Constant[] constants = cp.getConstantPool().getConstantPool(); switch (c.getTag()) { case Const.CONSTANT_String: { - ConstantString s = (ConstantString) c; - ConstantUtf8 u8 = (ConstantUtf8) constants[s.getStringIndex()]; + final ConstantString s = (ConstantString) c; + final ConstantUtf8 u8 = (ConstantUtf8) constants[s.getStringIndex()]; return addString(u8.getBytes()); } case Const.CONSTANT_Class: { - ConstantClass s = (ConstantClass) c; - ConstantUtf8 u8 = (ConstantUtf8) constants[s.getNameIndex()]; + final ConstantClass s = (ConstantClass) c; + final ConstantUtf8 u8 = (ConstantUtf8) constants[s.getNameIndex()]; return addClass(u8.getBytes()); } case Const.CONSTANT_NameAndType: { - ConstantNameAndType n = (ConstantNameAndType) c; - ConstantUtf8 u8 = (ConstantUtf8) constants[n.getNameIndex()]; - ConstantUtf8 u8_2 = (ConstantUtf8) constants[n.getSignatureIndex()]; + final ConstantNameAndType n = (ConstantNameAndType) c; + final ConstantUtf8 u8 = (ConstantUtf8) constants[n.getNameIndex()]; + final ConstantUtf8 u8_2 = (ConstantUtf8) constants[n.getSignatureIndex()]; return addNameAndType(u8.getBytes(), u8_2.getBytes()); } case Const.CONSTANT_Utf8: @@ -809,15 +809,15 @@ public class ConstantPoolGen { case Const.CONSTANT_InterfaceMethodref: case Const.CONSTANT_Methodref: case Const.CONSTANT_Fieldref: { - ConstantCP m = (ConstantCP) c; - ConstantClass clazz = (ConstantClass) constants[m.getClassIndex()]; - ConstantNameAndType n = (ConstantNameAndType) constants[m.getNameAndTypeIndex()]; + final ConstantCP m = (ConstantCP) c; + final ConstantClass clazz = (ConstantClass) constants[m.getClassIndex()]; + final ConstantNameAndType n = (ConstantNameAndType) constants[m.getNameAndTypeIndex()]; ConstantUtf8 u8 = (ConstantUtf8) constants[clazz.getNameIndex()]; - String class_name = u8.getBytes().replace('/', '.'); + final String class_name = u8.getBytes().replace('/', '.'); u8 = (ConstantUtf8) constants[n.getNameIndex()]; - String name = u8.getBytes(); + final String name = u8.getBytes(); u8 = (ConstantUtf8) constants[n.getSignatureIndex()]; - String signature = u8.getBytes(); + final String signature = u8.getBytes(); switch (c.getTag()) { case Const.CONSTANT_InterfaceMethodref: return addInterfaceMethodref(class_name, name, signature); diff --git a/src/main/java/org/apache/bcel/generic/ElementValueGen.java b/src/main/java/org/apache/bcel/generic/ElementValueGen.java index bce1da17..27f182ee 100644 --- a/src/main/java/org/apache/bcel/generic/ElementValueGen.java +++ b/src/main/java/org/apache/bcel/generic/ElementValueGen.java @@ -95,7 +95,7 @@ public abstract class ElementValueGen public static ElementValueGen readElementValue(final DataInput dis, final ConstantPoolGen cpGen) throws IOException { - int type = dis.readUnsignedByte(); + final int type = dis.readUnsignedByte(); switch (type) { case 'B': // byte @@ -137,8 +137,8 @@ public abstract class ElementValueGen new AnnotationEntryGen(AnnotationEntry.read(dis, cpGen .getConstantPool(), true), cpGen, false), cpGen); case '[': // Array - int numArrayVals = dis.readUnsignedShort(); - ElementValue[] evalues = new ElementValue[numArrayVals]; + final int numArrayVals = dis.readUnsignedShort(); + final ElementValue[] evalues = new ElementValue[numArrayVals]; for (int j = 0; j < numArrayVals; j++) { evalues[j] = ElementValue.readElementValue(dis, cpGen diff --git a/src/main/java/org/apache/bcel/generic/ElementValuePairGen.java b/src/main/java/org/apache/bcel/generic/ElementValuePairGen.java index f5b557d7..aa703d98 100644 --- a/src/main/java/org/apache/bcel/generic/ElementValuePairGen.java +++ b/src/main/java/org/apache/bcel/generic/ElementValuePairGen.java @@ -63,7 +63,7 @@ public class ElementValuePairGen */ public ElementValuePair getElementNameValuePair() { - ElementValue immutableValue = value.getElementValue(); + final ElementValue immutableValue = value.getElementValue(); return new ElementValuePair(nameIdx, immutableValue, cpool .getConstantPool()); } diff --git a/src/main/java/org/apache/bcel/generic/EnumElementValueGen.java b/src/main/java/org/apache/bcel/generic/EnumElementValueGen.java index edf69fc8..73626f0c 100644 --- a/src/main/java/org/apache/bcel/generic/EnumElementValueGen.java +++ b/src/main/java/org/apache/bcel/generic/EnumElementValueGen.java @@ -99,7 +99,7 @@ public class EnumElementValueGen extends ElementValueGen @Override public String stringifyValue() { - ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(valueIdx); + final ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(valueIdx); return cu8.getBytes(); // ConstantString cu8 = // (ConstantString)getConstantPool().getConstant(valueIdx); diff --git a/src/main/java/org/apache/bcel/generic/FieldGen.java b/src/main/java/org/apache/bcel/generic/FieldGen.java index 7548e03f..0a4d577f 100644 --- a/src/main/java/org/apache/bcel/generic/FieldGen.java +++ b/src/main/java/org/apache/bcel/generic/FieldGen.java @@ -47,8 +47,8 @@ public class FieldGen extends FieldGenOrMethodGen { @Override public boolean equals( final Object o1, final Object o2 ) { - FieldGen THIS = (FieldGen) o1; - FieldGen THAT = (FieldGen) o2; + final FieldGen THIS = (FieldGen) o1; + final FieldGen THAT = (FieldGen) o2; return THIS.getName().equals(THAT.getName()) && THIS.getSignature().equals(THAT.getSignature()); } @@ -56,7 +56,7 @@ public class FieldGen extends FieldGenOrMethodGen { @Override public int hashCode( final Object o ) { - FieldGen THIS = (FieldGen) o; + final FieldGen THIS = (FieldGen) o; return THIS.getSignature().hashCode() ^ THIS.getName().hashCode(); } }; @@ -88,14 +88,14 @@ public class FieldGen extends FieldGenOrMethodGen { */ public FieldGen(final Field field, final ConstantPoolGen cp) { this(field.getAccessFlags(), Type.getType(field.getSignature()), field.getName(), cp); - Attribute[] attrs = field.getAttributes(); - for (Attribute attr : attrs) { + final Attribute[] attrs = field.getAttributes(); + for (final Attribute attr : attrs) { if (attr instanceof ConstantValue) { setValue(((ConstantValue) attr).getConstantValueIndex()); } else if (attr instanceof Annotations) { - Annotations runtimeAnnotations = (Annotations)attr; - AnnotationEntry[] annotationEntries = runtimeAnnotations.getAnnotationEntries(); - for (AnnotationEntry element : annotationEntries) { + final Annotations runtimeAnnotations = (Annotations)attr; + final AnnotationEntry[] annotationEntries = runtimeAnnotations.getAnnotationEntries(); + for (final AnnotationEntry element : annotationEntries) { addAnnotationEntry(new AnnotationEntryGen(element,cp,false)); } } else { @@ -106,8 +106,8 @@ public class FieldGen extends FieldGenOrMethodGen { private void setValue( final int index ) { - ConstantPool cp = super.getConstantPool().getConstantPool(); - Constant c = cp.getConstant(index); + final ConstantPool cp = super.getConstantPool().getConstantPool(); + final Constant c = cp.getConstant(index); value = ((ConstantObject) c).getConstantValue(cp); } @@ -213,12 +213,12 @@ public class FieldGen extends FieldGenOrMethodGen { * Get field object after having set up all necessary values. */ public Field getField() { - String signature = getSignature(); - int name_index = super.getConstantPool().addUtf8(super.getName()); - int signature_index = super.getConstantPool().addUtf8(signature); + final String signature = getSignature(); + final int name_index = super.getConstantPool().addUtf8(super.getName()); + final int signature_index = super.getConstantPool().addUtf8(signature); if (value != null) { checkType(super.getType()); - int index = addConstant(); + final int index = addConstant(); addAttribute(new ConstantValue(super.getConstantPool().addUtf8("ConstantValue"), 2, index, super.getConstantPool().getConstantPool())); // sic } @@ -228,8 +228,8 @@ public class FieldGen extends FieldGenOrMethodGen { } private void addAnnotationsAsAttribute(final ConstantPoolGen cp) { - Attribute[] attrs = AnnotationEntryGen.getAnnotationAttributes(cp, super.getAnnotationEntries()); - for (Attribute attr : attrs) { + final Attribute[] attrs = AnnotationEntryGen.getAnnotationAttributes(cp, super.getAnnotationEntries()); + for (final Attribute attr : attrs) { addAttribute(attr); } } @@ -290,7 +290,7 @@ public class FieldGen extends FieldGenOrMethodGen { */ public void update() { if (observers != null) { - for (FieldObserver observer : observers ) { + for (final FieldObserver observer : observers ) { observer.notify(this); } } @@ -320,9 +320,9 @@ public class FieldGen extends FieldGenOrMethodGen { access = access.isEmpty() ? "" : (access + " "); signature = super.getType().toString(); name = getName(); - StringBuilder buf = new StringBuilder(32); // CHECKSTYLE IGNORE MagicNumber + final StringBuilder buf = new StringBuilder(32); // CHECKSTYLE IGNORE MagicNumber buf.append(access).append(signature).append(" ").append(name); - String value = getInitValue(); + final String value = getInitValue(); if (value != null) { buf.append(" = ").append(value); } @@ -333,7 +333,7 @@ public class FieldGen extends FieldGenOrMethodGen { /** @return deep copy of this field */ public FieldGen copy( final ConstantPoolGen cp ) { - FieldGen fg = (FieldGen) clone(); + final FieldGen fg = (FieldGen) clone(); fg.setConstantPool(cp); return fg; } diff --git a/src/main/java/org/apache/bcel/generic/FieldGenOrMethodGen.java b/src/main/java/org/apache/bcel/generic/FieldGenOrMethodGen.java index 84d249bf..ed5d706d 100644 --- a/src/main/java/org/apache/bcel/generic/FieldGenOrMethodGen.java +++ b/src/main/java/org/apache/bcel/generic/FieldGenOrMethodGen.java @@ -163,13 +163,13 @@ public abstract class FieldGenOrMethodGen extends AccessFlags implements NamedAn * @return all attributes of this method. */ public Attribute[] getAttributes() { - Attribute[] attributes = new Attribute[attribute_vec.size()]; + final Attribute[] attributes = new Attribute[attribute_vec.size()]; attribute_vec.toArray(attributes); return attributes; } public AnnotationEntryGen[] getAnnotationEntries() { - AnnotationEntryGen[] annotations = new AnnotationEntryGen[annotation_vec.size()]; + final AnnotationEntryGen[] annotations = new AnnotationEntryGen[annotation_vec.size()]; annotation_vec.toArray(annotations); return annotations; } @@ -184,7 +184,7 @@ public abstract class FieldGenOrMethodGen extends AccessFlags implements NamedAn public Object clone() { try { return super.clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { throw new Error("Clone Not Supported"); // never happens } } diff --git a/src/main/java/org/apache/bcel/generic/FieldOrMethod.java b/src/main/java/org/apache/bcel/generic/FieldOrMethod.java index 9392faae..a52a9836 100644 --- a/src/main/java/org/apache/bcel/generic/FieldOrMethod.java +++ b/src/main/java/org/apache/bcel/generic/FieldOrMethod.java @@ -50,9 +50,9 @@ public abstract class FieldOrMethod extends CPInstruction implements LoadClass { /** @return signature of referenced method/field. */ public String getSignature( final ConstantPoolGen cpg ) { - ConstantPool cp = cpg.getConstantPool(); - ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex()); - ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(cmr.getNameAndTypeIndex()); + final ConstantPool cp = cpg.getConstantPool(); + final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex()); + final ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(cmr.getNameAndTypeIndex()); return ((ConstantUtf8) cp.getConstant(cnat.getSignatureIndex())).getBytes(); } @@ -60,9 +60,9 @@ public abstract class FieldOrMethod extends CPInstruction implements LoadClass { /** @return name of referenced method/field. */ public String getName( final ConstantPoolGen cpg ) { - ConstantPool cp = cpg.getConstantPool(); - ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex()); - ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(cmr.getNameAndTypeIndex()); + final ConstantPool cp = cpg.getConstantPool(); + final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex()); + final ConstantNameAndType cnat = (ConstantNameAndType) cp.getConstant(cmr.getNameAndTypeIndex()); return ((ConstantUtf8) cp.getConstant(cnat.getNameIndex())).getBytes(); } @@ -80,9 +80,9 @@ public abstract class FieldOrMethod extends CPInstruction implements LoadClass { */ @Deprecated public String getClassName( final ConstantPoolGen cpg ) { - ConstantPool cp = cpg.getConstantPool(); - ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex()); - String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class); + final ConstantPool cp = cpg.getConstantPool(); + final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex()); + final String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class); if (className.startsWith("[")) { // Turn array classes into java.lang.Object. return "java.lang.Object"; @@ -111,8 +111,8 @@ public abstract class FieldOrMethod extends CPInstruction implements LoadClass { * type is an array class) */ public ReferenceType getReferenceType( final ConstantPoolGen cpg ) { - ConstantPool cp = cpg.getConstantPool(); - ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex()); + final ConstantPool cp = cpg.getConstantPool(); + final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex()); String className = cp.getConstantString(cmr.getClassIndex(), Const.CONSTANT_Class); if (className.startsWith("[")) { return (ArrayType) Type.getType(className); @@ -130,7 +130,7 @@ public abstract class FieldOrMethod extends CPInstruction implements LoadClass { */ @Override public ObjectType getLoadClassType( final ConstantPoolGen cpg ) { - ReferenceType rt = getReferenceType(cpg); + final ReferenceType rt = getReferenceType(cpg); if(rt instanceof ObjectType) { return (ObjectType)rt; } diff --git a/src/main/java/org/apache/bcel/generic/GOTO.java b/src/main/java/org/apache/bcel/generic/GOTO.java index 5b3b2990..ec131d09 100644 --- a/src/main/java/org/apache/bcel/generic/GOTO.java +++ b/src/main/java/org/apache/bcel/generic/GOTO.java @@ -68,11 +68,11 @@ public class GOTO extends GotoInstruction implements VariableLengthInstruction { */ @Override protected int updatePosition( final int offset, final int max_offset ) { - int i = getTargetOffset(); // Depending on old position value + final int i = getTargetOffset(); // Depending on old position value setPosition(getPosition() + offset); // Position may be shifted by preceding expansions if (Math.abs(i) >= (Short.MAX_VALUE - max_offset)) { // to large for short (estimate) super.setOpcode(org.apache.bcel.Const.GOTO_W); - short old_length = (short) super.getLength(); + final short old_length = (short) super.getLength(); super.setLength(5); return super.getLength() - old_length; } diff --git a/src/main/java/org/apache/bcel/generic/INVOKEDYNAMIC.java b/src/main/java/org/apache/bcel/generic/INVOKEDYNAMIC.java index 7750342d..3eab6daf 100644 --- a/src/main/java/org/apache/bcel/generic/INVOKEDYNAMIC.java +++ b/src/main/java/org/apache/bcel/generic/INVOKEDYNAMIC.java @@ -123,8 +123,8 @@ public class INVOKEDYNAMIC extends InvokeInstruction { */ @Override public String getClassName( final ConstantPoolGen cpg ) { - ConstantPool cp = cpg.getConstantPool(); - ConstantInvokeDynamic cid = (ConstantInvokeDynamic) cp.getConstant(super.getIndex(), Const.CONSTANT_InvokeDynamic); + final ConstantPool cp = cpg.getConstantPool(); + final ConstantInvokeDynamic cid = (ConstantInvokeDynamic) cp.getConstant(super.getIndex(), Const.CONSTANT_InvokeDynamic); return ((ConstantNameAndType) cp.getConstant(cid.getNameAndTypeIndex())).getName(cp); } } diff --git a/src/main/java/org/apache/bcel/generic/Instruction.java b/src/main/java/org/apache/bcel/generic/Instruction.java index 51f65ecf..5befdcbd 100644 --- a/src/main/java/org/apache/bcel/generic/Instruction.java +++ b/src/main/java/org/apache/bcel/generic/Instruction.java @@ -126,7 +126,7 @@ public abstract class Instruction implements Cloneable { } else { try { i = (Instruction) clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { System.err.println(e); } } diff --git a/src/main/java/org/apache/bcel/generic/InstructionFactory.java b/src/main/java/org/apache/bcel/generic/InstructionFactory.java index eed04372..11e3d85e 100644 --- a/src/main/java/org/apache/bcel/generic/InstructionFactory.java +++ b/src/main/java/org/apache/bcel/generic/InstructionFactory.java @@ -86,8 +86,8 @@ public class InstructionFactory implements InstructionConstants { final Type[] arg_types, final short kind ) { int index; int nargs = 0; - String signature = Type.getMethodSignature(ret_type, arg_types); - for (Type arg_type : arg_types) { + final String signature = Type.getMethodSignature(ret_type, arg_types); + for (final Type arg_type : arg_types) { nargs += arg_type.getSize(); } if (kind == Const.INVOKEINTERFACE) { @@ -143,9 +143,9 @@ public class InstructionFactory implements InstructionConstants { * @param s the string to print */ public InstructionList createPrintln( final String s ) { - InstructionList il = new InstructionList(); - int out = cp.addFieldref("java.lang.System", "out", "Ljava/io/PrintStream;"); - int println = cp.addMethodref("java.io.PrintStream", "println", "(Ljava/lang/String;)V"); + final InstructionList il = new InstructionList(); + final int out = cp.addFieldref("java.lang.System", "out", "Ljava/io/PrintStream;"); + final int println = cp.addMethodref("java.io.PrintStream", "println", "(Ljava/lang/String;)V"); il.append(new GETSTATIC(out)); il.append(new PUSH(cp, s)); il.append(new INVOKEVIRTUAL(println)); @@ -238,7 +238,7 @@ public class InstructionFactory implements InstructionConstants { public Instruction createAppend( final Type type ) { - byte t = type.getType(); + final byte t = type.getType(); if (isString(type)) { return createInvoke(append_mos[0], Const.INVOKEVIRTUAL); } @@ -271,7 +271,7 @@ public class InstructionFactory implements InstructionConstants { */ public FieldInstruction createFieldAccess( final String class_name, final String name, final Type type, final short kind ) { int index; - String signature = type.getSignature(); + final String signature = type.getSignature(); index = cp.addFieldref(class_name, name, signature); switch (kind) { case Const.GETFIELD: @@ -420,7 +420,7 @@ public class InstructionFactory implements InstructionConstants { * @param op operation, such as "+", "*", "<<", etc. */ public static ArithmeticInstruction createBinaryOperation( final String op, final Type type ) { - char first = op.charAt(0); + final char first = op.charAt(0); switch (type.getType()) { case Const.T_BYTE: case Const.T_SHORT: @@ -586,18 +586,18 @@ public class InstructionFactory implements InstructionConstants { */ public Instruction createCast( final Type src_type, final Type dest_type ) { if ((src_type instanceof BasicType) && (dest_type instanceof BasicType)) { - byte dest = dest_type.getType(); + final byte dest = dest_type.getType(); byte src = src_type.getType(); if (dest == Const.T_LONG && (src == Const.T_CHAR || src == Const.T_BYTE || src == Const.T_SHORT)) { src = Const.T_INT; } - String name = "org.apache.bcel.generic." + short_names[src - Const.T_CHAR] + "2" + final String name = "org.apache.bcel.generic." + short_names[src - Const.T_CHAR] + "2" + short_names[dest - Const.T_CHAR]; Instruction i = null; try { i = (Instruction) java.lang.Class.forName(name).newInstance(); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException("Could not find instruction: " + name, e); } return i; diff --git a/src/main/java/org/apache/bcel/generic/InstructionHandle.java b/src/main/java/org/apache/bcel/generic/InstructionHandle.java index 490b0ff1..216d203a 100644 --- a/src/main/java/org/apache/bcel/generic/InstructionHandle.java +++ b/src/main/java/org/apache/bcel/generic/InstructionHandle.java @@ -103,7 +103,7 @@ public class InstructionHandle { // See BCEL-273 // TODO remove this method in any redesign of BCEL public Instruction swapInstruction( final Instruction i ) { - Instruction oldInstruction = instruction; + final Instruction oldInstruction = instruction; instruction = i; return oldInstruction; } @@ -122,7 +122,7 @@ public class InstructionHandle { if (ih_list == null) { return new InstructionHandle(i); } - InstructionHandle ih = ih_list; + final InstructionHandle ih = ih_list; ih_list = ih.next; ih.setInstruction(i); return ih; @@ -227,7 +227,7 @@ public class InstructionHandle { if (!hasTargeters()) { return new InstructionTargeter[0]; } - InstructionTargeter[] t = new InstructionTargeter[targeters.size()]; + final InstructionTargeter[] t = new InstructionTargeter[targeters.size()]; targeters.toArray(t); return t; } diff --git a/src/main/java/org/apache/bcel/generic/InstructionList.java b/src/main/java/org/apache/bcel/generic/InstructionList.java index 97973926..8138c511 100644 --- a/src/main/java/org/apache/bcel/generic/InstructionList.java +++ b/src/main/java/org/apache/bcel/generic/InstructionList.java @@ -113,8 +113,8 @@ public class InstructionList implements Iterable<InstructionHandle> { * Do a binary search since the pos array is orderd. */ do { - int i = (l + r) / 2; - int j = pos[i]; + final int i = (l + r) / 2; + final int j = pos[i]; if (j == target) { return ihs[i]; } else if (target < j) { @@ -135,7 +135,7 @@ public class InstructionList implements Iterable<InstructionHandle> { * @return target position's instruction handle if available */ public InstructionHandle findHandle(final int pos) { - int[] positions = byte_positions; + final int[] positions = byte_positions; InstructionHandle ih = start; for (int i = 0; i < length; i++) { if (positions[i] == pos) { @@ -164,12 +164,12 @@ public class InstructionList implements Iterable<InstructionHandle> { */ while (bytes.available() > 0) { // Remember byte offset and associate it with the instruction - int off = bytes.getIndex(); + final int off = bytes.getIndex(); pos[count] = off; /* * Read one instruction from the byte stream, the byte position is set accordingly. */ - Instruction i = Instruction.readInstruction(bytes); + final Instruction i = Instruction.readInstruction(bytes); InstructionHandle ih; if (i instanceof BranchInstruction) { ih = append((BranchInstruction) i); @@ -180,7 +180,7 @@ public class InstructionList implements Iterable<InstructionHandle> { ihs[count] = ih; count++; } - } catch (IOException e) { + } catch (final IOException e) { throw new ClassGenException(e.toString(), e); } byte_positions = new int[count]; // Trim to proper size @@ -190,7 +190,7 @@ public class InstructionList implements Iterable<InstructionHandle> { */ for (int i = 0; i < count; i++) { if (ihs[i] instanceof BranchHandle) { - BranchInstruction bi = (BranchInstruction) ihs[i].getInstruction(); + final BranchInstruction bi = (BranchInstruction) ihs[i].getInstruction(); int target = bi.getPosition() + bi.getIndex(); /* * Byte code position: relative -> absolute. */ @@ -202,8 +202,8 @@ public class InstructionList implements Iterable<InstructionHandle> { bi.setTarget(ih); // Update target // If it is a Select instruction, update all branch targets if (bi instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH - Select s = (Select) bi; - int[] indices = s.getIndices(); + final Select s = (Select) bi; + final int[] indices = s.getIndices(); for (int j = 0; j < indices.length; j++) { target = bi.getPosition() + indices[j]; ih = findHandle(ihs, pos, count, target); @@ -233,8 +233,8 @@ public class InstructionList implements Iterable<InstructionHandle> { if (il.isEmpty()) { return ih; } - InstructionHandle next = ih.getNext(); - InstructionHandle ret = il.start; + final InstructionHandle next = ih.getNext(); + final InstructionHandle ret = il.start; ih.setNext(il.start); il.start.setPrev(ih); il.end.setNext(next); @@ -316,7 +316,7 @@ public class InstructionList implements Iterable<InstructionHandle> { * @return instruction handle of the appended instruction */ public InstructionHandle append(final Instruction i) { - InstructionHandle ih = InstructionHandle.getInstructionHandle(i); + final InstructionHandle ih = InstructionHandle.getInstructionHandle(i); append(ih); return ih; } @@ -329,7 +329,7 @@ public class InstructionList implements Iterable<InstructionHandle> { * @return branch instruction handle of the appended instruction */ public BranchHandle append(final BranchInstruction i) { - BranchHandle ih = BranchHandle.getBranchHandle(i); + final BranchHandle ih = BranchHandle.getBranchHandle(i); append(ih); return ih; } @@ -407,8 +407,8 @@ public class InstructionList implements Iterable<InstructionHandle> { * @return instruction handle pointing to the <B>first</B> appended instruction */ public BranchHandle append(final InstructionHandle ih, final BranchInstruction i) { - BranchHandle bh = BranchHandle.getBranchHandle(i); - InstructionList il = new InstructionList(); + final BranchHandle bh = BranchHandle.getBranchHandle(i); + final InstructionList il = new InstructionList(); il.append(bh); append(ih, il); return bh; @@ -430,8 +430,8 @@ public class InstructionList implements Iterable<InstructionHandle> { if (il.isEmpty()) { return ih; } - InstructionHandle prev = ih.getPrev(); - InstructionHandle ret = il.start; + final InstructionHandle prev = ih.getPrev(); + final InstructionHandle ret = il.start; ih.setPrev(il.end); il.end.setNext(ih); il.start.setPrev(prev); @@ -504,7 +504,7 @@ public class InstructionList implements Iterable<InstructionHandle> { * @return instruction handle of the inserted instruction */ public InstructionHandle insert(final Instruction i) { - InstructionHandle ih = InstructionHandle.getInstructionHandle(i); + final InstructionHandle ih = InstructionHandle.getInstructionHandle(i); insert(ih); return ih; } @@ -517,7 +517,7 @@ public class InstructionList implements Iterable<InstructionHandle> { * @return branch instruction handle of the appended instruction */ public BranchHandle insert(final BranchInstruction i) { - BranchHandle ih = BranchHandle.getBranchHandle(i); + final BranchHandle ih = BranchHandle.getBranchHandle(i); insert(ih); return ih; } @@ -595,8 +595,8 @@ public class InstructionList implements Iterable<InstructionHandle> { * @return instruction handle of the first inserted instruction */ public BranchHandle insert(final InstructionHandle ih, final BranchInstruction i) { - BranchHandle bh = BranchHandle.getBranchHandle(i); - InstructionList il = new InstructionList(); + final BranchHandle bh = BranchHandle.getBranchHandle(i); + final InstructionList il = new InstructionList(); il.append(bh); insert(ih, il); return bh; @@ -630,7 +630,7 @@ public class InstructionList implements Iterable<InstructionHandle> { } } // Step 2: Temporarily remove the given instructions from the list - InstructionHandle prev = start.getPrev(); + final InstructionHandle prev = start.getPrev(); InstructionHandle next = end.getNext(); if (prev != null) { prev.setNext(next); @@ -709,11 +709,11 @@ public class InstructionList implements Iterable<InstructionHandle> { } first.setPrev(null); // Completely separated from rest of list last.setNext(null); - List<InstructionHandle> target_vec = new ArrayList<>(); + final List<InstructionHandle> target_vec = new ArrayList<>(); for (InstructionHandle ih = first; ih != null; ih = ih.getNext()) { ih.getInstruction().dispose(); // e.g. BranchInstructions release their targets } - StringBuilder buf = new StringBuilder("{ "); + final StringBuilder buf = new StringBuilder("{ "); for (InstructionHandle ih = first; ih != null; ih = next) { next = ih.getNext(); length--; @@ -727,7 +727,7 @@ public class InstructionList implements Iterable<InstructionHandle> { } buf.append("}"); if (!target_vec.isEmpty()) { - InstructionHandle[] targeted = new InstructionHandle[target_vec.size()]; + final InstructionHandle[] targeted = new InstructionHandle[target_vec.size()]; target_vec.toArray(targeted); throw new TargetLostException(targeted, buf.toString()); } @@ -854,21 +854,21 @@ public class InstructionList implements Iterable<InstructionHandle> { int additional_bytes = 0; int index = 0; int count = 0; - int[] pos = new int[length]; + final int[] pos = new int[length]; /* * Pass 0: Sanity checks */ if (check) { for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { - Instruction i = ih.getInstruction(); + final Instruction i = ih.getInstruction(); if (i instanceof BranchInstruction) { // target instruction within list? Instruction inst = ((BranchInstruction) i).getTarget().getInstruction(); if (!contains(inst)) { throw new ClassGenException("Branch target of " + Const.getOpcodeName(i.getOpcode()) + ":" + inst + " not in instruction list"); } if (i instanceof Select) { - InstructionHandle[] targets = ((Select) i).getTargets(); - for (InstructionHandle target : targets) { + final InstructionHandle[] targets = ((Select) i).getTargets(); + for (final InstructionHandle target : targets) { inst = target.getInstruction(); if (!contains(inst)) { throw new ClassGenException("Branch target of " + Const.getOpcodeName(i.getOpcode()) + ":" + inst + " not in instruction list"); @@ -886,7 +886,7 @@ public class InstructionList implements Iterable<InstructionHandle> { * Pass 1: Set position numbers and sum up the maximum number of bytes an instruction may be shifted. */ for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { - Instruction i = ih.getInstruction(); + final Instruction i = ih.getInstruction(); ih.setPosition(index); pos[count++] = index; /* @@ -917,7 +917,7 @@ public class InstructionList implements Iterable<InstructionHandle> { */ index = count = 0; for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { - Instruction i = ih.getInstruction(); + final Instruction i = ih.getInstruction(); ih.setPosition(index); pos[count++] = index; index += i.getLength(); @@ -934,15 +934,15 @@ public class InstructionList implements Iterable<InstructionHandle> { public byte[] getByteCode() { // Update position indices of instructions setPositions(); - ByteArrayOutputStream b = new ByteArrayOutputStream(); - DataOutputStream out = new DataOutputStream(b); + final ByteArrayOutputStream b = new ByteArrayOutputStream(); + final DataOutputStream out = new DataOutputStream(b); try { for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { - Instruction i = ih.getInstruction(); + final Instruction i = ih.getInstruction(); i.dump(out); // Traverse list } out.flush(); - } catch (IOException e) { + } catch (final IOException e) { System.err.println(e); return new byte[0]; } @@ -953,12 +953,12 @@ public class InstructionList implements Iterable<InstructionHandle> { * @return an array of instructions without target information for branch instructions. */ public Instruction[] getInstructions() { - List<Instruction> instructions = new ArrayList<>(); + final List<Instruction> instructions = new ArrayList<>(); try (ByteSequence bytes = new ByteSequence(getByteCode())) { while (bytes.available() > 0) { instructions.add(Instruction.readInstruction(bytes)); } - } catch (IOException e) { + } catch (final IOException e) { throw new ClassGenException(e.toString(), e); } return instructions.toArray(new Instruction[instructions.size()]); @@ -975,7 +975,7 @@ public class InstructionList implements Iterable<InstructionHandle> { * @return String containing all instructions in this list. */ public String toString(final boolean verbose) { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { buf.append(ih.toString(verbose)).append("\n"); } @@ -996,7 +996,7 @@ public class InstructionList implements Iterable<InstructionHandle> { if (ih == null) { throw new NoSuchElementException(); } - InstructionHandle i = ih; + final InstructionHandle i = ih; ih = ih.getNext(); return i; } @@ -1017,7 +1017,7 @@ public class InstructionList implements Iterable<InstructionHandle> { * @return array containing all instructions (handles) */ public InstructionHandle[] getInstructionHandles() { - InstructionHandle[] ihs = new InstructionHandle[length]; + final InstructionHandle[] ihs = new InstructionHandle[length]; InstructionHandle ih = start; for (int i = 0; i < length; i++) { ihs[i] = ih; @@ -1040,14 +1040,14 @@ public class InstructionList implements Iterable<InstructionHandle> { * @return complete, i.e., deep copy of this list */ public InstructionList copy() { - Map<InstructionHandle, InstructionHandle> map = new HashMap<>(); - InstructionList il = new InstructionList(); + final Map<InstructionHandle, InstructionHandle> map = new HashMap<>(); + final InstructionList il = new InstructionList(); /* * Pass 1: Make copies of all instructions, append them to the new list and associate old instruction references with the new ones, i.e., a 1:1 mapping. */ for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { - Instruction i = ih.getInstruction(); - Instruction c = i.copy(); // Use clone for shallow copy + final Instruction i = ih.getInstruction(); + final Instruction c = i.copy(); // Use clone for shallow copy if (c instanceof BranchInstruction) { map.put(ih, il.append((BranchInstruction) c)); } else { @@ -1060,17 +1060,17 @@ public class InstructionList implements Iterable<InstructionHandle> { InstructionHandle ih = start; InstructionHandle ch = il.start; while (ih != null) { - Instruction i = ih.getInstruction(); - Instruction c = ch.getInstruction(); + final Instruction i = ih.getInstruction(); + final Instruction c = ch.getInstruction(); if (i instanceof BranchInstruction) { - BranchInstruction bi = (BranchInstruction) i; - BranchInstruction bc = (BranchInstruction) c; - InstructionHandle itarget = bi.getTarget(); // old target + final BranchInstruction bi = (BranchInstruction) i; + final BranchInstruction bc = (BranchInstruction) c; + final InstructionHandle itarget = bi.getTarget(); // old target // New target is in hash map bc.setTarget(map.get(itarget)); if (bi instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH - InstructionHandle[] itargets = ((Select) bi).getTargets(); - InstructionHandle[] ctargets = ((Select) bc).getTargets(); + final InstructionHandle[] itargets = ((Select) bi).getTargets(); + final InstructionHandle[] ctargets = ((Select) bc).getTargets(); for (int j = 0; j < itargets.length; j++) { // Update all targets ctargets[j] = map.get(itargets[j]); } @@ -1087,10 +1087,10 @@ public class InstructionList implements Iterable<InstructionHandle> { */ public void replaceConstantPool(final ConstantPoolGen old_cp, final ConstantPoolGen new_cp) { for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { - Instruction i = ih.getInstruction(); + final Instruction i = ih.getInstruction(); if (i instanceof CPInstruction) { - CPInstruction ci = (CPInstruction) i; - Constant c = old_cp.getConstant(ci.getIndex()); + final CPInstruction ci = (CPInstruction) i; + final Constant c = old_cp.getConstant(ci.getIndex()); ci.setIndex(new_cp.addConstant(c, old_cp)); } } @@ -1154,15 +1154,15 @@ public class InstructionList implements Iterable<InstructionHandle> { */ public void redirectBranches(final InstructionHandle old_target, final InstructionHandle new_target) { for (InstructionHandle ih = start; ih != null; ih = ih.getNext()) { - Instruction i = ih.getInstruction(); + final Instruction i = ih.getInstruction(); if (i instanceof BranchInstruction) { - BranchInstruction b = (BranchInstruction) i; - InstructionHandle target = b.getTarget(); + final BranchInstruction b = (BranchInstruction) i; + final InstructionHandle target = b.getTarget(); if (target == old_target) { b.setTarget(new_target); } if (b instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH - InstructionHandle[] targets = ((Select) b).getTargets(); + final InstructionHandle[] targets = ((Select) b).getTargets(); for (int j = 0; j < targets.length; j++) { if (targets[j] == old_target) { ((Select) b).setTarget(j, new_target); @@ -1185,9 +1185,9 @@ public class InstructionList implements Iterable<InstructionHandle> { * @see MethodGen */ public void redirectLocalVariables(final LocalVariableGen[] lg, final InstructionHandle old_target, final InstructionHandle new_target) { - for (LocalVariableGen element : lg) { - InstructionHandle start = element.getStart(); - InstructionHandle end = element.getEnd(); + for (final LocalVariableGen element : lg) { + final InstructionHandle start = element.getStart(); + final InstructionHandle end = element.getEnd(); if (start == old_target) { element.setStart(new_target); } @@ -1209,7 +1209,7 @@ public class InstructionList implements Iterable<InstructionHandle> { * @see MethodGen */ public void redirectExceptionHandlers(final CodeExceptionGen[] exceptions, final InstructionHandle old_target, final InstructionHandle new_target) { - for (CodeExceptionGen exception : exceptions) { + for (final CodeExceptionGen exception : exceptions) { if (exception.getStartPC() == old_target) { exception.setStartPC(new_target); } @@ -1249,7 +1249,7 @@ public class InstructionList implements Iterable<InstructionHandle> { */ public void update() { if (observers != null) { - for (InstructionListObserver observer : observers) { + for (final InstructionListObserver observer : observers) { observer.notify(this); } } diff --git a/src/main/java/org/apache/bcel/generic/InvokeInstruction.java b/src/main/java/org/apache/bcel/generic/InvokeInstruction.java index 56a396b1..9c821ea8 100644 --- a/src/main/java/org/apache/bcel/generic/InvokeInstruction.java +++ b/src/main/java/org/apache/bcel/generic/InvokeInstruction.java @@ -52,8 +52,8 @@ public abstract class InvokeInstruction extends FieldOrMethod implements Excepti */ @Override public String toString( final ConstantPool cp ) { - Constant c = cp.getConstant(super.getIndex()); - StringTokenizer tok = new StringTokenizer(cp.constantToString(c)); + final Constant c = cp.getConstant(super.getIndex()); + final StringTokenizer tok = new StringTokenizer(cp.constantToString(c)); return Const.getOpcodeName(super.getOpcode()) + " " + tok.nextToken().replace('.', '/') + tok.nextToken(); } @@ -73,7 +73,7 @@ public abstract class InvokeInstruction extends FieldOrMethod implements Excepti sum = 1; // this reference } - String signature = getSignature(cpg); + final String signature = getSignature(cpg); sum += Type.getArgumentTypesSize(signature); return sum; } @@ -86,7 +86,7 @@ public abstract class InvokeInstruction extends FieldOrMethod implements Excepti */ @Override public int produceStack( final ConstantPoolGen cpg ) { - String signature = getSignature(cpg); + final String signature = getSignature(cpg); return Type.getReturnTypeSize(signature); } diff --git a/src/main/java/org/apache/bcel/generic/JSR.java b/src/main/java/org/apache/bcel/generic/JSR.java index 3feced9f..6fd7668e 100644 --- a/src/main/java/org/apache/bcel/generic/JSR.java +++ b/src/main/java/org/apache/bcel/generic/JSR.java @@ -59,11 +59,11 @@ public class JSR extends JsrInstruction implements VariableLengthInstruction { @Override protected int updatePosition( final int offset, final int max_offset ) { - int i = getTargetOffset(); // Depending on old position value + final int i = getTargetOffset(); // Depending on old position value setPosition(getPosition() + offset); // Position may be shifted by preceding expansions if (Math.abs(i) >= (Short.MAX_VALUE - max_offset)) { // to large for short (estimate) super.setOpcode(org.apache.bcel.Const.JSR_W); - short old_length = (short) super.getLength(); + final short old_length = (short) super.getLength(); super.setLength(5); return super.getLength() - old_length; } diff --git a/src/main/java/org/apache/bcel/generic/JsrInstruction.java b/src/main/java/org/apache/bcel/generic/JsrInstruction.java index c24c3fa3..d0317e3f 100644 --- a/src/main/java/org/apache/bcel/generic/JsrInstruction.java +++ b/src/main/java/org/apache/bcel/generic/JsrInstruction.java @@ -67,7 +67,7 @@ public abstract class JsrInstruction extends BranchInstruction implements Uncond while (ih.getInstruction() != this) { ih = ih.getNext(); } - InstructionHandle toThis = ih; + final InstructionHandle toThis = ih; while (ih != null) { ih = ih.getNext(); if ((ih != null) && (ih.getInstruction() == this)) { diff --git a/src/main/java/org/apache/bcel/generic/LDC.java b/src/main/java/org/apache/bcel/generic/LDC.java index 61a4a8df..b99f851c 100644 --- a/src/main/java/org/apache/bcel/generic/LDC.java +++ b/src/main/java/org/apache/bcel/generic/LDC.java @@ -97,7 +97,7 @@ public class LDC extends CPInstruction implements PushInstruction, ExceptionThro org.apache.bcel.classfile.Constant c = cpg.getConstantPool().getConstant(super.getIndex()); switch (c.getTag()) { case org.apache.bcel.Const.CONSTANT_String: - int i = ((org.apache.bcel.classfile.ConstantString) c).getStringIndex(); + final int i = ((org.apache.bcel.classfile.ConstantString) c).getStringIndex(); c = cpg.getConstantPool().getConstant(i); return ((org.apache.bcel.classfile.ConstantUtf8) c).getBytes(); case org.apache.bcel.Const.CONSTANT_Float: @@ -105,7 +105,7 @@ public class LDC extends CPInstruction implements PushInstruction, ExceptionThro case org.apache.bcel.Const.CONSTANT_Integer: return Integer.valueOf(((org.apache.bcel.classfile.ConstantInteger) c).getBytes()); case org.apache.bcel.Const.CONSTANT_Class: - int nameIndex = ((org.apache.bcel.classfile.ConstantClass) c).getNameIndex(); + final int nameIndex = ((org.apache.bcel.classfile.ConstantClass) c).getNameIndex(); c = cpg.getConstantPool().getConstant(nameIndex); return new ObjectType(((org.apache.bcel.classfile.ConstantUtf8) c).getBytes()); default: // Never reached diff --git a/src/main/java/org/apache/bcel/generic/LDC2_W.java b/src/main/java/org/apache/bcel/generic/LDC2_W.java index 1f02857d..529c01b4 100644 --- a/src/main/java/org/apache/bcel/generic/LDC2_W.java +++ b/src/main/java/org/apache/bcel/generic/LDC2_W.java @@ -53,7 +53,7 @@ public class LDC2_W extends CPInstruction implements PushInstruction { public Number getValue( final ConstantPoolGen cpg ) { - org.apache.bcel.classfile.Constant c = cpg.getConstantPool().getConstant(super.getIndex()); + final org.apache.bcel.classfile.Constant c = cpg.getConstantPool().getConstant(super.getIndex()); switch (c.getTag()) { case org.apache.bcel.Const.CONSTANT_Long: return Long.valueOf(((org.apache.bcel.classfile.ConstantLong) c).getBytes()); diff --git a/src/main/java/org/apache/bcel/generic/LineNumberGen.java b/src/main/java/org/apache/bcel/generic/LineNumberGen.java index 92468baf..68c2596a 100644 --- a/src/main/java/org/apache/bcel/generic/LineNumberGen.java +++ b/src/main/java/org/apache/bcel/generic/LineNumberGen.java @@ -90,7 +90,7 @@ public class LineNumberGen implements InstructionTargeter, Cloneable { public Object clone() { try { return super.clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { throw new Error("Clone Not Supported"); // never happens } } diff --git a/src/main/java/org/apache/bcel/generic/LocalVariableGen.java b/src/main/java/org/apache/bcel/generic/LocalVariableGen.java index f96d4f39..98c33bcb 100644 --- a/src/main/java/org/apache/bcel/generic/LocalVariableGen.java +++ b/src/main/java/org/apache/bcel/generic/LocalVariableGen.java @@ -86,8 +86,8 @@ public class LocalVariableGen implements InstructionTargeter, NamedAndTyped, Clo length += end.getInstruction().getLength(); } } - int name_index = cp.addUtf8(name); - int signature_index = cp.addUtf8(type.getSignature()); + final int name_index = cp.addUtf8(name); + final int signature_index = cp.addUtf8(type.getSignature()); return new LocalVariable(start_pc, length, name_index, signature_index, index, cp .getConstantPool()); } @@ -204,7 +204,7 @@ public class LocalVariableGen implements InstructionTargeter, NamedAndTyped, Clo if (!(o instanceof LocalVariableGen)) { return false; } - LocalVariableGen l = (LocalVariableGen) o; + final LocalVariableGen l = (LocalVariableGen) o; return (l.index == index) && (l.start == start) && (l.end == end); } @@ -219,7 +219,7 @@ public class LocalVariableGen implements InstructionTargeter, NamedAndTyped, Clo public Object clone() { try { return super.clone(); - } catch (CloneNotSupportedException e) { + } catch (final CloneNotSupportedException e) { throw new Error("Clone Not Supported"); // never happens } } diff --git a/src/main/java/org/apache/bcel/generic/MethodGen.java b/src/main/java/org/apache/bcel/generic/MethodGen.java index 2e3df555..58b94ae7 100644 --- a/src/main/java/org/apache/bcel/generic/MethodGen.java +++ b/src/main/java/org/apache/bcel/generic/MethodGen.java @@ -79,8 +79,8 @@ public class MethodGen extends FieldGenOrMethodGen { @Override public boolean equals( final Object o1, final Object o2 ) { - MethodGen THIS = (MethodGen) o1; - MethodGen THAT = (MethodGen) o2; + final MethodGen THIS = (MethodGen) o1; + final MethodGen THAT = (MethodGen) o2; return THIS.getName().equals(THAT.getName()) && THIS.getSignature().equals(THAT.getSignature()); } @@ -88,7 +88,7 @@ public class MethodGen extends FieldGenOrMethodGen { @Override public int hashCode( final Object o ) { - MethodGen THIS = (MethodGen) o; + final MethodGen THIS = (MethodGen) o; return THIS.getSignature().hashCode() ^ THIS.getName().hashCode(); } }; @@ -126,7 +126,7 @@ public class MethodGen extends FieldGenOrMethodGen { setClassName(class_name); setInstructionList(il); setConstantPool(cp); - boolean abstract_ = isAbstract() || isNative(); + final boolean abstract_ = isAbstract() || isNative(); InstructionHandle start = null; InstructionHandle end = null; if (!abstract_) { @@ -139,8 +139,8 @@ public class MethodGen extends FieldGenOrMethodGen { } } if (arg_types != null) { - int size = arg_types.length; - for (Type arg_type : arg_types) { + final int size = arg_types.length; + for (final Type arg_type : arg_types) { if (Type.VOID == arg_type) { throw new ClassGenException("'void' is an illegal argument type for a method"); } @@ -180,25 +180,25 @@ public class MethodGen extends FieldGenOrMethodGen { ((m.getAccessFlags() & (Const.ACC_ABSTRACT | Const.ACC_NATIVE)) == 0) ? new InstructionList(m.getCode().getCode()) : null, cp); - Attribute[] attributes = m.getAttributes(); - for (Attribute attribute : attributes) { + final Attribute[] attributes = m.getAttributes(); + for (final Attribute attribute : attributes) { Attribute a = attribute; if (a instanceof Code) { - Code c = (Code) a; + final Code c = (Code) a; setMaxStack(c.getMaxStack()); setMaxLocals(c.getMaxLocals()); - CodeException[] ces = c.getExceptionTable(); + final CodeException[] ces = c.getExceptionTable(); if (ces != null) { - for (CodeException ce : ces) { - int type = ce.getCatchType(); + for (final CodeException ce : ces) { + final int type = ce.getCatchType(); ObjectType c_type = null; if (type > 0) { - String cen = m.getConstantPool().getConstantString(type, + final String cen = m.getConstantPool().getConstantString(type, Const.CONSTANT_Class); c_type = ObjectType.getInstance(cen); } - int end_pc = ce.getEndPC(); - int length = m.getCode().getCode().length; + final int end_pc = ce.getEndPC(); + final int length = m.getCode().getCode().length; InstructionHandle end; if (length == end_pc) { // May happen, because end_pc is exclusive end = il.getEnd(); @@ -210,21 +210,21 @@ public class MethodGen extends FieldGenOrMethodGen { .getHandlerPC()), c_type); } } - Attribute[] c_attributes = c.getAttributes(); - for (Attribute c_attribute : c_attributes) { + final Attribute[] c_attributes = c.getAttributes(); + for (final Attribute c_attribute : c_attributes) { a = c_attribute; if (a instanceof LineNumberTable) { - LineNumber[] ln = ((LineNumberTable) a).getLineNumberTable(); - for (LineNumber l : ln) { - InstructionHandle ih = il.findHandle(l.getStartPC()); + final LineNumber[] ln = ((LineNumberTable) a).getLineNumberTable(); + for (final LineNumber l : ln) { + final InstructionHandle ih = il.findHandle(l.getStartPC()); if (ih != null) { addLineNumber(ih, l.getLineNumber()); } } } else if (a instanceof LocalVariableTable) { - LocalVariable[] lv = ((LocalVariableTable) a).getLocalVariableTable(); + final LocalVariable[] lv = ((LocalVariableTable) a).getLocalVariableTable(); removeLocalVariables(); - for (LocalVariable l : lv) { + for (final LocalVariable l : lv) { InstructionHandle start = il.findHandle(l.getStartPC()); InstructionHandle end = il.findHandle(l.getStartPC() + l.getLength()); // Repair malformed handles @@ -242,14 +242,14 @@ public class MethodGen extends FieldGenOrMethodGen { } } } else if (a instanceof ExceptionTable) { - String[] names = ((ExceptionTable) a).getExceptionNames(); - for (String name2 : names) { + final String[] names = ((ExceptionTable) a).getExceptionNames(); + for (final String name2 : names) { addException(name2); } } else if (a instanceof Annotations) { - Annotations runtimeAnnotations = (Annotations) a; - AnnotationEntry[] aes = runtimeAnnotations.getAnnotationEntries(); - for (AnnotationEntry element : aes) { + final Annotations runtimeAnnotations = (Annotations) a; + final AnnotationEntry[] aes = runtimeAnnotations.getAnnotationEntries(); + for (final AnnotationEntry element : aes) { addAnnotationEntry(new AnnotationEntryGen(element, cp, false)); } } else { @@ -273,13 +273,13 @@ public class MethodGen extends FieldGenOrMethodGen { */ public LocalVariableGen addLocalVariable( final String name, final Type type, final int slot, final InstructionHandle start, final InstructionHandle end ) { - byte t = type.getType(); + final byte t = type.getType(); if (t != Const.T_ADDRESS) { - int add = type.getSize(); + final int add = type.getSize(); if (slot + add > max_locals) { max_locals = slot + add; } - LocalVariableGen l = new LocalVariableGen(slot, name, type, start, end); + final LocalVariableGen l = new LocalVariableGen(slot, name, type, start, end); int i; if ((i = variable_vec.indexOf(l)) >= 0) { variable_vec.set(i, l); @@ -325,7 +325,7 @@ public class MethodGen extends FieldGenOrMethodGen { * Remove all local variables. */ public void removeLocalVariables() { - for (LocalVariableGen lv : variable_vec) { + for (final LocalVariableGen lv : variable_vec) { lv.dispose(); } variable_vec.clear(); @@ -339,8 +339,8 @@ public class MethodGen extends FieldGenOrMethodGen { * @return array of declared local variables sorted by index */ public LocalVariableGen[] getLocalVariables() { - int size = variable_vec.size(); - LocalVariableGen[] lg = new LocalVariableGen[size]; + final int size = variable_vec.size(); + final LocalVariableGen[] lg = new LocalVariableGen[size]; variable_vec.toArray(lg); for (int i = 0; i < size; i++) { if ((lg[i].getStart() == null) && (il != null)) { @@ -366,9 +366,9 @@ public class MethodGen extends FieldGenOrMethodGen { * @return `LocalVariableTable' attribute of all the local variables of this method. */ public LocalVariableTable getLocalVariableTable( final ConstantPoolGen cp ) { - LocalVariableGen[] lg = getLocalVariables(); - int size = lg.length; - LocalVariable[] lv = new LocalVariable[size]; + final LocalVariableGen[] lg = getLocalVariables(); + final int size = lg.length; + final LocalVariable[] lv = new LocalVariable[size]; for (int i = 0; i < size; i++) { lv[i] = lg[i].getLocalVariable(cp); } @@ -385,7 +385,7 @@ public class MethodGen extends FieldGenOrMethodGen { * @see LineNumber */ public LineNumberGen addLineNumber( final InstructionHandle ih, final int src_line ) { - LineNumberGen l = new LineNumberGen(ih, src_line); + final LineNumberGen l = new LineNumberGen(ih, src_line); line_number_vec.add(l); return l; } @@ -411,7 +411,7 @@ public class MethodGen extends FieldGenOrMethodGen { * @return array of line numbers */ public LineNumberGen[] getLineNumbers() { - LineNumberGen[] lg = new LineNumberGen[line_number_vec.size()]; + final LineNumberGen[] lg = new LineNumberGen[line_number_vec.size()]; line_number_vec.toArray(lg); return lg; } @@ -421,8 +421,8 @@ public class MethodGen extends FieldGenOrMethodGen { * @return `LineNumberTable' attribute of all the local variables of this method. */ public LineNumberTable getLineNumberTable( final ConstantPoolGen cp ) { - int size = line_number_vec.size(); - LineNumber[] ln = new LineNumber[size]; + final int size = line_number_vec.size(); + final LineNumber[] ln = new LineNumber[size]; for (int i = 0; i < size; i++) { ln[i] = line_number_vec.get(i).getLineNumber(); } @@ -447,7 +447,7 @@ public class MethodGen extends FieldGenOrMethodGen { if ((start_pc == null) || (end_pc == null) || (handler_pc == null)) { throw new ClassGenException("Exception handler target is null instruction"); } - CodeExceptionGen c = new CodeExceptionGen(start_pc, end_pc, handler_pc, catch_type); + final CodeExceptionGen c = new CodeExceptionGen(start_pc, end_pc, handler_pc, catch_type); exception_vec.add(c); return c; } @@ -473,7 +473,7 @@ public class MethodGen extends FieldGenOrMethodGen { * @return array of declared exception handlers */ public CodeExceptionGen[] getExceptionHandlers() { - CodeExceptionGen[] cg = new CodeExceptionGen[exception_vec.size()]; + final CodeExceptionGen[] cg = new CodeExceptionGen[exception_vec.size()]; exception_vec.toArray(cg); return cg; } @@ -483,10 +483,10 @@ public class MethodGen extends FieldGenOrMethodGen { * @return code exceptions for `Code' attribute */ private CodeException[] getCodeExceptions() { - int size = exception_vec.size(); - CodeException[] c_exc = new CodeException[size]; + final int size = exception_vec.size(); + final CodeException[] c_exc = new CodeException[size]; for (int i = 0; i < size; i++) { - CodeExceptionGen c = exception_vec.get(i); + final CodeExceptionGen c = exception_vec.get(i); c_exc[i] = c.getCodeException(super.getConstantPool()); } return c_exc; @@ -523,7 +523,7 @@ public class MethodGen extends FieldGenOrMethodGen { * @return array of thrown exceptions */ public String[] getExceptions() { - String[] e = new String[throws_vec.size()]; + final String[] e = new String[throws_vec.size()]; throws_vec.toArray(e); return e; } @@ -533,8 +533,8 @@ public class MethodGen extends FieldGenOrMethodGen { * @return `Exceptions' attribute of all the exceptions thrown by this method. */ private ExceptionTable getExceptionTable( final ConstantPoolGen cp ) { - int size = throws_vec.size(); - int[] ex = new int[size]; + final int size = throws_vec.size(); + final int[] ex = new int[size]; for (int i = 0; i < size; i++) { ex[i] = cp.addClass(throws_vec.get(i)); } @@ -576,7 +576,7 @@ public class MethodGen extends FieldGenOrMethodGen { * @return all attributes of this method. */ public Attribute[] getCodeAttributes() { - Attribute[] attributes = new Attribute[code_attrs_vec.size()]; + final Attribute[] attributes = new Attribute[code_attrs_vec.size()]; code_attrs_vec.toArray(attributes); return attributes; } @@ -585,8 +585,8 @@ public class MethodGen extends FieldGenOrMethodGen { * @since 6.0 */ public void addAnnotationsAsAttribute(final ConstantPoolGen cp) { - Attribute[] attrs = AnnotationEntryGen.getAnnotationAttributes(cp, super.getAnnotationEntries()); - for (Attribute attr : attrs) { + final Attribute[] attrs = AnnotationEntryGen.getAnnotationAttributes(cp, super.getAnnotationEntries()); + for (final Attribute attr : attrs) { addAttribute(attr); } } @@ -598,9 +598,9 @@ public class MethodGen extends FieldGenOrMethodGen { if (!hasParameterAnnotations) { return; } - Attribute[] attrs = AnnotationEntryGen.getParameterAnnotationAttributes(cp,param_annotations); + final Attribute[] attrs = AnnotationEntryGen.getParameterAnnotationAttributes(cp,param_annotations); if (attrs!=null) { - for (Attribute attr : attrs) { + for (final Attribute attr : attrs) { addAttribute(attr); } } @@ -614,10 +614,10 @@ public class MethodGen extends FieldGenOrMethodGen { * @return method object */ public Method getMethod() { - String signature = getSignature(); + final String signature = getSignature(); final ConstantPoolGen _cp = super.getConstantPool(); - int name_index = _cp.addUtf8(super.getName()); - int signature_index = _cp.addUtf8(signature); + final int name_index = _cp.addUtf8(super.getName()); + final int signature_index = _cp.addUtf8(signature); /* Also updates positions of instructions, i.e., their indices */ byte[] byte_code = null; @@ -634,20 +634,20 @@ public class MethodGen extends FieldGenOrMethodGen { if ((line_number_vec.size() > 0) && !strip_attributes) { addCodeAttribute(lnt = getLineNumberTable(_cp)); } - Attribute[] code_attrs = getCodeAttributes(); + final Attribute[] code_attrs = getCodeAttributes(); /* Each attribute causes 6 additional header bytes */ int attrs_len = 0; - for (Attribute code_attr : code_attrs) { + for (final Attribute code_attr : code_attrs) { attrs_len += code_attr.getLength() + 6; } - CodeException[] c_exc = getCodeExceptions(); - int exc_len = c_exc.length * 8; // Every entry takes 8 bytes + final CodeException[] c_exc = getCodeExceptions(); + final int exc_len = c_exc.length * 8; // Every entry takes 8 bytes Code code = null; if ((il != null) && !isAbstract() && !isNative()) { // Remove any stale code attribute - Attribute[] attributes = getAttributes(); - for (Attribute a : attributes) { + final Attribute[] attributes = getAttributes(); + for (final Attribute a : attributes) { if (a instanceof Code) { removeAttribute(a); } @@ -665,7 +665,7 @@ public class MethodGen extends FieldGenOrMethodGen { addAttribute(et = getExceptionTable(_cp)); // Add `Exceptions' if there are "throws" clauses } - Method m = new Method(super.getAccessFlags(), name_index, signature_index, getAttributes(), _cp + final Method m = new Method(super.getAccessFlags(), name_index, signature_index, getAttributes(), _cp .getConstantPool()); // Undo effects of adding attributes if (lvt != null) { @@ -699,9 +699,9 @@ public class MethodGen extends FieldGenOrMethodGen { if ((next != null) && (ih.getInstruction() instanceof NOP)) { try { il.delete(ih); - } catch (TargetLostException e) { - for (InstructionHandle target : e.getTargets()) { - for (InstructionTargeter targeter : target.getTargeters()) { + } catch (final TargetLostException e) { + for (final InstructionHandle target : e.getTargets()) { + for (final InstructionTargeter targeter : target.getTargeters()) { targeter.updateTarget(target, next); } } @@ -835,15 +835,15 @@ public class MethodGen extends FieldGenOrMethodGen { if (il != null) { int max = isStatic() ? 0 : 1; if (arg_types != null) { - for (Type arg_type : arg_types) { + for (final Type arg_type : arg_types) { max += arg_type.getSize(); } } for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { - Instruction ins = ih.getInstruction(); + final Instruction ins = ih.getInstruction(); if ((ins instanceof LocalVariableInstruction) || (ins instanceof RET) || (ins instanceof IINC)) { - int index = ((IndexedInstruction) ins).getIndex() + final int index = ((IndexedInstruction) ins).getIndex() + ((TypedInstruction) ins).getType(super.getConstantPool()).getSize(); if (index > max) { max = index; @@ -892,7 +892,7 @@ public class MethodGen extends FieldGenOrMethodGen { public BranchTarget pop() { if (!branchTargets.empty()) { - BranchTarget bt = branchTargets.pop(); + final BranchTarget bt = branchTargets.pop(); return bt; } return null; @@ -900,7 +900,7 @@ public class MethodGen extends FieldGenOrMethodGen { private BranchTarget visit( final InstructionHandle target, final int stackDepth ) { - BranchTarget bt = new BranchTarget(target, stackDepth); + final BranchTarget bt = new BranchTarget(target, stackDepth); visitedTargets.put(target, bt); return bt; } @@ -918,14 +918,14 @@ public class MethodGen extends FieldGenOrMethodGen { * @return maximum stack depth used by method */ public static int getMaxStack( final ConstantPoolGen cp, final InstructionList il, final CodeExceptionGen[] et ) { - BranchStack branchTargets = new BranchStack(); + final BranchStack branchTargets = new BranchStack(); /* Initially, populate the branch stack with the exception * handlers, because these aren't (necessarily) branched to * explicitly. in each case, the stack will have depth 1, * containing the exception object. */ - for (CodeExceptionGen element : et) { - InstructionHandle handler_pc = element.getHandlerPC(); + for (final CodeExceptionGen element : et) { + final InstructionHandle handler_pc = element.getHandlerPC(); if (handler_pc != null) { branchTargets.push(handler_pc, 1); } @@ -934,21 +934,21 @@ public class MethodGen extends FieldGenOrMethodGen { int maxStackDepth = 0; InstructionHandle ih = il.getStart(); while (ih != null) { - Instruction instruction = ih.getInstruction(); - short opcode = instruction.getOpcode(); - int delta = instruction.produceStack(cp) - instruction.consumeStack(cp); + final Instruction instruction = ih.getInstruction(); + final short opcode = instruction.getOpcode(); + final int delta = instruction.produceStack(cp) - instruction.consumeStack(cp); stackDepth += delta; if (stackDepth > maxStackDepth) { maxStackDepth = stackDepth; } // choose the next instruction based on whether current is a branch. if (instruction instanceof BranchInstruction) { - BranchInstruction branch = (BranchInstruction) instruction; + final BranchInstruction branch = (BranchInstruction) instruction; if (instruction instanceof Select) { // explore all of the select's targets. the default target is handled below. - Select select = (Select) branch; - InstructionHandle[] targets = select.getTargets(); - for (InstructionHandle target : targets) { + final Select select = (Select) branch; + final InstructionHandle[] targets = select.getTargets(); + for (final InstructionHandle target : targets) { branchTargets.push(target, stackDepth); } // nothing to fall through to. @@ -978,7 +978,7 @@ public class MethodGen extends FieldGenOrMethodGen { } // if we have no more instructions, see if there are any deferred branches to explore. if (ih == null) { - BranchTarget bt = branchTargets.pop(); + final BranchTarget bt = branchTargets.pop(); if (bt != null) { ih = bt.target; stackDepth = bt.stackDepth; @@ -1016,7 +1016,7 @@ public class MethodGen extends FieldGenOrMethodGen { */ public void update() { if (observers != null) { - for (MethodObserver observer : observers) { + for (final MethodObserver observer : observers) { observer.notify(this); } } @@ -1031,19 +1031,19 @@ public class MethodGen extends FieldGenOrMethodGen { */ @Override public final String toString() { - String access = Utility.accessToString(super.getAccessFlags()); + final String access = Utility.accessToString(super.getAccessFlags()); String signature = Type.getMethodSignature(super.getType(), arg_types); signature = Utility.methodSignatureToString(signature, super.getName(), access, true, getLocalVariableTable(super.getConstantPool())); - StringBuilder buf = new StringBuilder(signature); - for (Attribute a : getAttributes()) { + final StringBuilder buf = new StringBuilder(signature); + for (final Attribute a : getAttributes()) { if (!((a instanceof Code) || (a instanceof ExceptionTable))) { buf.append(" [").append(a).append("]"); } } if (throws_vec.size() > 0) { - for (String throwsDescriptor : throws_vec) { + for (final String throwsDescriptor : throws_vec) { buf.append("\n\t\tthrows ").append(throwsDescriptor); } } @@ -1054,8 +1054,8 @@ public class MethodGen extends FieldGenOrMethodGen { /** @return deep copy of this method */ public MethodGen copy( final String class_name, final ConstantPoolGen cp ) { - Method m = ((MethodGen) clone()).getMethod(); - MethodGen mg = new MethodGen(m, class_name, super.getConstantPool()); + final Method m = ((MethodGen) clone()).getMethod(); + final MethodGen mg = new MethodGen(m, class_name, super.getConstantPool()); if (super.getConstantPool() != cp) { mg.setConstantPool(cp); mg.getInstructionList().replaceConstantPool(super.getConstantPool(), cp); @@ -1091,10 +1091,10 @@ public class MethodGen extends FieldGenOrMethodGen { return; } // Find attributes that contain parameter annotation data - Attribute[] attrs = getAttributes(); + final Attribute[] attrs = getAttributes(); ParameterAnnotations paramAnnVisAttr = null; ParameterAnnotations paramAnnInvisAttr = null; - for (Attribute attribute : attrs) { + for (final Attribute attribute : attrs) { if (attribute instanceof ParameterAnnotations) { // Initialize param_annotations @@ -1108,7 +1108,7 @@ public class MethodGen extends FieldGenOrMethodGen { } } hasParameterAnnotations = true; - ParameterAnnotations rpa = (ParameterAnnotations) attribute; + final ParameterAnnotations rpa = (ParameterAnnotations) attribute; if (rpa instanceof RuntimeVisibleParameterAnnotations) { paramAnnVisAttr = rpa; } else { @@ -1117,10 +1117,10 @@ public class MethodGen extends FieldGenOrMethodGen { for (int j = 0; j < arg_types.length; j++) { // This returns Annotation[] ... - ParameterAnnotationEntry immutableArray = rpa + final ParameterAnnotationEntry immutableArray = rpa .getParameterAnnotationEntries()[j]; // ... which needs transforming into an AnnotationGen[] ... - List<AnnotationEntryGen> mutable = makeMutableVersion(immutableArray.getAnnotationEntries()); + final List<AnnotationEntryGen> mutable = makeMutableVersion(immutableArray.getAnnotationEntries()); // ... then add these to any we already know about param_annotations[j].addAll(mutable); } @@ -1137,8 +1137,8 @@ public class MethodGen extends FieldGenOrMethodGen { private List<AnnotationEntryGen> makeMutableVersion(final AnnotationEntry[] mutableArray) { - List<AnnotationEntryGen> result = new ArrayList<>(); - for (AnnotationEntry element : mutableArray) { + final List<AnnotationEntryGen> result = new ArrayList<>(); + for (final AnnotationEntry element : mutableArray) { result.add(new AnnotationEntryGen(element, getConstantPool(), false)); } @@ -1156,14 +1156,14 @@ public class MethodGen extends FieldGenOrMethodGen { param_annotations = parmList; hasParameterAnnotations = true; } - List<AnnotationEntryGen> existingAnnotations = param_annotations[parameterIndex]; + final List<AnnotationEntryGen> existingAnnotations = param_annotations[parameterIndex]; if (existingAnnotations != null) { existingAnnotations.add(annotation); } else { - List<AnnotationEntryGen> l = new ArrayList<>(); + final List<AnnotationEntryGen> l = new ArrayList<>(); l.add(annotation); param_annotations[parameterIndex] = l; } diff --git a/src/main/java/org/apache/bcel/generic/NameSignatureInstruction.java b/src/main/java/org/apache/bcel/generic/NameSignatureInstruction.java index f98cbb05..b04ac61b 100644 --- a/src/main/java/org/apache/bcel/generic/NameSignatureInstruction.java +++ b/src/main/java/org/apache/bcel/generic/NameSignatureInstruction.java @@ -40,23 +40,23 @@ public abstract class NameSignatureInstruction extends CPInstruction { } public ConstantNameAndType getNameAndType(final ConstantPoolGen cpg) { - ConstantPool cp = cpg.getConstantPool(); - ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex()); + final ConstantPool cp = cpg.getConstantPool(); + final ConstantCP cmr = (ConstantCP) cp.getConstant(super.getIndex()); return (ConstantNameAndType) cp.getConstant(cmr.getNameAndTypeIndex()); } /** @return signature of referenced method/field. */ public String getSignature(final ConstantPoolGen cpg) { - ConstantPool cp = cpg.getConstantPool(); - ConstantNameAndType cnat = getNameAndType(cpg); + final ConstantPool cp = cpg.getConstantPool(); + final ConstantNameAndType cnat = getNameAndType(cpg); return ((ConstantUtf8) cp.getConstant(cnat.getSignatureIndex())).getBytes(); } /** @return name of referenced method/field. */ public String getName(final ConstantPoolGen cpg) { - ConstantPool cp = cpg.getConstantPool(); - ConstantNameAndType cnat = getNameAndType(cpg); + final ConstantPool cp = cpg.getConstantPool(); + final ConstantNameAndType cnat = getNameAndType(cpg); return ((ConstantUtf8) cp.getConstant(cnat.getNameIndex())).getBytes(); } diff --git a/src/main/java/org/apache/bcel/generic/ObjectType.java b/src/main/java/org/apache/bcel/generic/ObjectType.java index 0f9c1758..6e8c5a39 100644 --- a/src/main/java/org/apache/bcel/generic/ObjectType.java +++ b/src/main/java/org/apache/bcel/generic/ObjectType.java @@ -81,9 +81,9 @@ public class ObjectType extends ReferenceType { @Deprecated public boolean referencesClass() { try { - JavaClass jc = Repository.lookupClass(class_name); + final JavaClass jc = Repository.lookupClass(class_name); return jc.isClass(); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { return false; } } @@ -99,9 +99,9 @@ public class ObjectType extends ReferenceType { @Deprecated public boolean referencesInterface() { try { - JavaClass jc = Repository.lookupClass(class_name); + final JavaClass jc = Repository.lookupClass(class_name); return !jc.isClass(); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { return false; } } @@ -116,7 +116,7 @@ public class ObjectType extends ReferenceType { * referenced by this type can't be found */ public boolean referencesClassExact() throws ClassNotFoundException { - JavaClass jc = Repository.lookupClass(class_name); + final JavaClass jc = Repository.lookupClass(class_name); return jc.isClass(); } @@ -130,7 +130,7 @@ public class ObjectType extends ReferenceType { * referenced by this type can't be found */ public boolean referencesInterfaceExact() throws ClassNotFoundException { - JavaClass jc = Repository.lookupClass(class_name); + final JavaClass jc = Repository.lookupClass(class_name); return !jc.isClass(); } @@ -154,11 +154,11 @@ public class ObjectType extends ReferenceType { * can't be found */ public boolean accessibleTo( final ObjectType accessor ) throws ClassNotFoundException { - JavaClass jc = Repository.lookupClass(class_name); + final JavaClass jc = Repository.lookupClass(class_name); if (jc.isPublic()) { return true; } - JavaClass acc = Repository.lookupClass(accessor.class_name); + final JavaClass acc = Repository.lookupClass(accessor.class_name); return acc.getPackageName().equals(jc.getPackageName()); } } diff --git a/src/main/java/org/apache/bcel/generic/ReferenceType.java b/src/main/java/org/apache/bcel/generic/ReferenceType.java index d3ac34ac..143b1718 100644 --- a/src/main/java/org/apache/bcel/generic/ReferenceType.java +++ b/src/main/java/org/apache/bcel/generic/ReferenceType.java @@ -73,7 +73,7 @@ public abstract class ReferenceType extends Type { if (!(t instanceof ReferenceType)) { return false; } - ReferenceType T = (ReferenceType) t; + final ReferenceType T = (ReferenceType) t; if (this.equals(Type.NULL)) { return true; // This is not explicitely stated, but clear. Isn't it? } @@ -141,8 +141,8 @@ public abstract class ReferenceType extends Type { if (T instanceof ArrayType) { /* TC and SC are the same primitive type (�2.4.1). */ - Type sc = ((ArrayType) this).getElementType(); - Type tc = ((ArrayType) T).getElementType(); + final Type sc = ((ArrayType) this).getElementType(); + final Type tc = ((ArrayType) T).getElementType(); if (sc instanceof BasicType && tc instanceof BasicType && sc.equals(tc)) { return true; } @@ -161,7 +161,7 @@ public abstract class ReferenceType extends Type { // on one of them "interfaces implemented by arrays" is exchanged with "'Cloneable' or // 'java.io.Serializable'" if ((T instanceof ObjectType) && (((ObjectType) T).referencesInterfaceExact())) { - for (String element : Const.getInterfacesImplementedByArrays()) { + for (final String element : Const.getInterfacesImplementedByArrays()) { if (T.equals(ObjectType.getInstance(element))) { return true; } @@ -209,8 +209,8 @@ public abstract class ReferenceType extends Type { } /* This code is from a bug report by Konstantin Shagin <konst@cs.technion.ac.il> */ if ((this instanceof ArrayType) && (t instanceof ArrayType)) { - ArrayType arrType1 = (ArrayType) this; - ArrayType arrType2 = (ArrayType) t; + final ArrayType arrType1 = (ArrayType) this; + final ArrayType arrType2 = (ArrayType) t; if ((arrType1.getDimensions() == arrType2.getDimensions()) && arrType1.getBasicType() instanceof ObjectType && arrType2.getBasicType() instanceof ObjectType) { @@ -231,22 +231,22 @@ public abstract class ReferenceType extends Type { // superinterfaces or even castability or assignment compatibility. } // this and t are ObjectTypes, see above. - ObjectType thiz = (ObjectType) this; - ObjectType other = (ObjectType) t; - JavaClass[] thiz_sups = Repository.getSuperClasses(thiz.getClassName()); - JavaClass[] other_sups = Repository.getSuperClasses(other.getClassName()); + final ObjectType thiz = (ObjectType) this; + final ObjectType other = (ObjectType) t; + final JavaClass[] thiz_sups = Repository.getSuperClasses(thiz.getClassName()); + final JavaClass[] other_sups = Repository.getSuperClasses(other.getClassName()); if ((thiz_sups == null) || (other_sups == null)) { return null; } // Waaahh... - JavaClass[] this_sups = new JavaClass[thiz_sups.length + 1]; - JavaClass[] t_sups = new JavaClass[other_sups.length + 1]; + final JavaClass[] this_sups = new JavaClass[thiz_sups.length + 1]; + final JavaClass[] t_sups = new JavaClass[other_sups.length + 1]; System.arraycopy(thiz_sups, 0, this_sups, 1, thiz_sups.length); System.arraycopy(other_sups, 0, t_sups, 1, other_sups.length); this_sups[0] = Repository.lookupClass(thiz.getClassName()); t_sups[0] = Repository.lookupClass(other.getClassName()); - for (JavaClass t_sup : t_sups) { - for (JavaClass this_sup : this_sups) { + for (final JavaClass t_sup : t_sups) { + for (final JavaClass this_sup : this_sups) { if (this_sup.equals(t_sup)) { return ObjectType.getInstance(this_sup.getClassName()); } @@ -303,22 +303,22 @@ public abstract class ReferenceType extends Type { // superinterfaces or even castability or assignment compatibility. } // this and t are ObjectTypes, see above. - ObjectType thiz = (ObjectType) this; - ObjectType other = (ObjectType) t; - JavaClass[] thiz_sups = Repository.getSuperClasses(thiz.getClassName()); - JavaClass[] other_sups = Repository.getSuperClasses(other.getClassName()); + final ObjectType thiz = (ObjectType) this; + final ObjectType other = (ObjectType) t; + final JavaClass[] thiz_sups = Repository.getSuperClasses(thiz.getClassName()); + final JavaClass[] other_sups = Repository.getSuperClasses(other.getClassName()); if ((thiz_sups == null) || (other_sups == null)) { return null; } // Waaahh... - JavaClass[] this_sups = new JavaClass[thiz_sups.length + 1]; - JavaClass[] t_sups = new JavaClass[other_sups.length + 1]; + final JavaClass[] this_sups = new JavaClass[thiz_sups.length + 1]; + final JavaClass[] t_sups = new JavaClass[other_sups.length + 1]; System.arraycopy(thiz_sups, 0, this_sups, 1, thiz_sups.length); System.arraycopy(other_sups, 0, t_sups, 1, other_sups.length); this_sups[0] = Repository.lookupClass(thiz.getClassName()); t_sups[0] = Repository.lookupClass(other.getClassName()); - for (JavaClass t_sup : t_sups) { - for (JavaClass this_sup : this_sups) { + for (final JavaClass t_sup : t_sups) { + for (final JavaClass this_sup : this_sups) { if (this_sup.equals(t_sup)) { return ObjectType.getInstance(this_sup.getClassName()); } diff --git a/src/main/java/org/apache/bcel/generic/ReturnaddressType.java b/src/main/java/org/apache/bcel/generic/ReturnaddressType.java index d99d8fef..d61e9937 100644 --- a/src/main/java/org/apache/bcel/generic/ReturnaddressType.java +++ b/src/main/java/org/apache/bcel/generic/ReturnaddressType.java @@ -67,7 +67,7 @@ public class ReturnaddressType extends Type { if (!(rat instanceof ReturnaddressType)) { return false; } - ReturnaddressType that = (ReturnaddressType) rat; + final ReturnaddressType that = (ReturnaddressType) rat; if (this.returnTarget == null || that.returnTarget == null) { return that.returnTarget == this.returnTarget; } diff --git a/src/main/java/org/apache/bcel/generic/SWITCH.java b/src/main/java/org/apache/bcel/generic/SWITCH.java index 948a3ed7..c1fb9f6f 100644 --- a/src/main/java/org/apache/bcel/generic/SWITCH.java +++ b/src/main/java/org/apache/bcel/generic/SWITCH.java @@ -70,15 +70,15 @@ public final class SWITCH implements CompoundInstruction { private void fillup( final int max_gap, final InstructionHandle target ) { - int max_size = match_length + match_length * max_gap; - int[] m_vec = new int[max_size]; - InstructionHandle[] t_vec = new InstructionHandle[max_size]; + final int max_size = match_length + match_length * max_gap; + final int[] m_vec = new int[max_size]; + final InstructionHandle[] t_vec = new InstructionHandle[max_size]; int count = 1; m_vec[0] = match[0]; t_vec[0] = targets[0]; for (int i = 1; i < match_length; i++) { - int prev = match[i - 1]; - int gap = match[i] - prev; + final int prev = match[i - 1]; + final int gap = match[i] - prev; for (int j = 1; j < gap; j++) { m_vec[count] = prev + j; t_vec[count] = target; @@ -102,7 +102,7 @@ public final class SWITCH implements CompoundInstruction { int i = l; int j = r; int h; - int m = match[(l + r) / 2]; + final int m = match[(l + r) / 2]; InstructionHandle h2; do { while (match[i] < m) { diff --git a/src/main/java/org/apache/bcel/generic/Select.java b/src/main/java/org/apache/bcel/generic/Select.java index 00463be8..c2766af0 100644 --- a/src/main/java/org/apache/bcel/generic/Select.java +++ b/src/main/java/org/apache/bcel/generic/Select.java @@ -95,7 +95,7 @@ public abstract class Select extends BranchInstruction implements VariableLength this.targets = targets; // now it's safe to set default target setTarget(defaultTarget); - for (InstructionHandle target2 : targets) { + for (final InstructionHandle target2 : targets) { notifyTarget(null, target2, this); } if ((match_length = match.length) != targets.length) { @@ -122,7 +122,7 @@ public abstract class Select extends BranchInstruction implements VariableLength @Override protected int updatePosition( final int offset, final int max_offset ) { setPosition(getPosition() + offset); // Additional offset caused by preceding SWITCHs, GOTOs, etc. - short old_length = (short) super.getLength(); + final short old_length = (short) super.getLength(); /* Alignment on 4-byte-boundary, + 1, because of tag byte. */ padding = (4 - ((getPosition() + 1) % 4)) % 4; @@ -165,7 +165,7 @@ public abstract class Select extends BranchInstruction implements VariableLength */ @Override public String toString( final boolean verbose ) { - StringBuilder buf = new StringBuilder(super.toString(verbose)); + final StringBuilder buf = new StringBuilder(super.toString(verbose)); if (verbose) { for (int i = 0; i < match_length; i++) { String s = "null"; @@ -222,7 +222,7 @@ public abstract class Select extends BranchInstruction implements VariableLength if (super.getTarget() == ih) { return true; } - for (InstructionHandle target2 : targets) { + for (final InstructionHandle target2 : targets) { if (target2 == ih) { return true; } @@ -233,7 +233,7 @@ public abstract class Select extends BranchInstruction implements VariableLength @Override protected Object clone() throws CloneNotSupportedException { - Select copy = (Select) super.clone(); + final Select copy = (Select) super.clone(); copy.match = match.clone(); copy.indices = indices.clone(); copy.targets = targets.clone(); @@ -247,7 +247,7 @@ public abstract class Select extends BranchInstruction implements VariableLength @Override void dispose() { super.dispose(); - for (InstructionHandle target2 : targets) { + for (final InstructionHandle target2 : targets) { target2.removeTargeter(this); } } diff --git a/src/main/java/org/apache/bcel/generic/SimpleElementValueGen.java b/src/main/java/org/apache/bcel/generic/SimpleElementValueGen.java index 2a7abaee..f8334389 100644 --- a/src/main/java/org/apache/bcel/generic/SimpleElementValueGen.java +++ b/src/main/java/org/apache/bcel/generic/SimpleElementValueGen.java @@ -188,7 +188,7 @@ public class SimpleElementValueGen extends ElementValueGen throw new RuntimeException( "Dont call getValueString() on a non STRING ElementValue"); } - ConstantUtf8 c = (ConstantUtf8) getConstantPool().getConstant(idx); + final ConstantUtf8 c = (ConstantUtf8) getConstantPool().getConstant(idx); return c.getBytes(); } @@ -198,7 +198,7 @@ public class SimpleElementValueGen extends ElementValueGen throw new RuntimeException( "Dont call getValueString() on a non STRING ElementValue"); } - ConstantInteger c = (ConstantInteger) getConstantPool().getConstant(idx); + final ConstantInteger c = (ConstantInteger) getConstantPool().getConstant(idx); return c.getBytes(); } @@ -209,34 +209,34 @@ public class SimpleElementValueGen extends ElementValueGen switch (super.getElementValueType()) { case PRIMITIVE_INT: - ConstantInteger c = (ConstantInteger) getConstantPool().getConstant(idx); + final ConstantInteger c = (ConstantInteger) getConstantPool().getConstant(idx); return Integer.toString(c.getBytes()); case PRIMITIVE_LONG: - ConstantLong j = (ConstantLong) getConstantPool().getConstant(idx); + final ConstantLong j = (ConstantLong) getConstantPool().getConstant(idx); return Long.toString(j.getBytes()); case PRIMITIVE_DOUBLE: - ConstantDouble d = (ConstantDouble) getConstantPool().getConstant(idx); + final ConstantDouble d = (ConstantDouble) getConstantPool().getConstant(idx); return Double.toString(d.getBytes()); case PRIMITIVE_FLOAT: - ConstantFloat f = (ConstantFloat) getConstantPool().getConstant(idx); + final ConstantFloat f = (ConstantFloat) getConstantPool().getConstant(idx); return Float.toString(f.getBytes()); case PRIMITIVE_SHORT: - ConstantInteger s = (ConstantInteger) getConstantPool().getConstant(idx); + final ConstantInteger s = (ConstantInteger) getConstantPool().getConstant(idx); return Integer.toString(s.getBytes()); case PRIMITIVE_BYTE: - ConstantInteger b = (ConstantInteger) getConstantPool().getConstant(idx); + final ConstantInteger b = (ConstantInteger) getConstantPool().getConstant(idx); return Integer.toString(b.getBytes()); case PRIMITIVE_CHAR: - ConstantInteger ch = (ConstantInteger) getConstantPool().getConstant(idx); + final ConstantInteger ch = (ConstantInteger) getConstantPool().getConstant(idx); return Integer.toString(ch.getBytes()); case PRIMITIVE_BOOLEAN: - ConstantInteger bo = (ConstantInteger) getConstantPool().getConstant(idx); + final ConstantInteger bo = (ConstantInteger) getConstantPool().getConstant(idx); if (bo.getBytes() == 0) { return "false"; } return "true"; case STRING: - ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(idx); + final ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(idx); return cu8.getBytes(); default: throw new RuntimeException( diff --git a/src/main/java/org/apache/bcel/generic/TABLESWITCH.java b/src/main/java/org/apache/bcel/generic/TABLESWITCH.java index 29b582f7..3216cc2a 100644 --- a/src/main/java/org/apache/bcel/generic/TABLESWITCH.java +++ b/src/main/java/org/apache/bcel/generic/TABLESWITCH.java @@ -61,9 +61,9 @@ public class TABLESWITCH extends Select { public void dump( final DataOutputStream out ) throws IOException { super.dump(out); final int _match_length = getMatch_length(); - int low = (_match_length > 0) ? super.getMatch(0) : 0; + final int low = (_match_length > 0) ? super.getMatch(0) : 0; out.writeInt(low); - int high = (_match_length > 0) ? super.getMatch(_match_length - 1) : 0; + final int high = (_match_length > 0) ? super.getMatch(_match_length - 1) : 0; out.writeInt(high); for (int i = 0; i < _match_length; i++) { out.writeInt(setIndices(i, getTargetOffset(super.getTarget(i)))); @@ -77,8 +77,8 @@ public class TABLESWITCH extends Select { @Override protected void initFromFile( final ByteSequence bytes, final boolean wide ) throws IOException { super.initFromFile(bytes, wide); - int low = bytes.readInt(); - int high = bytes.readInt(); + final int low = bytes.readInt(); + final int high = bytes.readInt(); final int _match_length = high - low + 1; setMatch_length(_match_length); final short _fixed_length = (short) (13 + _match_length * 4); diff --git a/src/main/java/org/apache/bcel/generic/Type.java b/src/main/java/org/apache/bcel/generic/Type.java index ecbbe731..2cb3ad5b 100644 --- a/src/main/java/org/apache/bcel/generic/Type.java +++ b/src/main/java/org/apache/bcel/generic/Type.java @@ -87,7 +87,7 @@ public abstract class Type { @Override public boolean equals(final Object o) { if (o instanceof Type) { - Type t = (Type)o; + final Type t = (Type)o; return (type == t.type) && signature.equals(t.signature); } return false; @@ -157,9 +157,9 @@ public abstract class Type { * @return method signature for given type(s). */ public static String getMethodSignature( final Type return_type, final Type[] arg_types ) { - StringBuilder buf = new StringBuilder("("); + final StringBuilder buf = new StringBuilder("("); if (arg_types != null) { - for (Type arg_type : arg_types) { + for (final Type arg_type : arg_types) { buf.append(arg_type.getSignature()); } } @@ -194,7 +194,7 @@ public abstract class Type { */ // @since 6.0 no longer final public static Type getType( final String signature ) throws StringIndexOutOfBoundsException { - byte type = Utility.typeOfSignature(signature); + final byte type = Utility.typeOfSignature(signature); if (type <= Const.T_VOID) { //corrected concurrent private static field acess wrap(consumed_chars, 1); @@ -205,16 +205,16 @@ public abstract class Type { dim++; } while (signature.charAt(dim) == '['); // Recurse, but just once, if the signature is ok - Type t = getType(signature.substring(dim)); + final Type t = getType(signature.substring(dim)); //corrected concurrent private static field acess // consumed_chars += dim; // update counter - is replaced by - int _temp = unwrap(consumed_chars) + dim; + final int _temp = unwrap(consumed_chars) + dim; wrap(consumed_chars, _temp); return new ArrayType(t, dim); } else { // type == T_REFERENCE // Utility.signatureToString understands how to parse // generic types. - String parsedSignature = Utility.signatureToString(signature, false); + final String parsedSignature = Utility.signatureToString(signature, false); wrap(consumed_chars, parsedSignature.length() + 2); // "Lblabla;" `L' and `;' are removed return ObjectType.getInstance(parsedSignature.replace('/', '.')); } @@ -230,9 +230,9 @@ public abstract class Type { public static Type getReturnType( final String signature ) { try { // Read return type after `)' - int index = signature.lastIndexOf(')') + 1; + final int index = signature.lastIndexOf(')') + 1; return getType(signature.substring(index)); - } catch (StringIndexOutOfBoundsException e) { // Should never occur + } catch (final StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); } } @@ -244,7 +244,7 @@ public abstract class Type { * @return array of argument types */ public static Type[] getArgumentTypes( final String signature ) { - List<Type> vec = new ArrayList<>(); + final List<Type> vec = new ArrayList<>(); int index; Type[] types; try { // Read all declarations between for `(' and `)' @@ -257,7 +257,7 @@ public abstract class Type { //corrected concurrent private static field acess index += unwrap(consumed_chars); // update position } - } catch (StringIndexOutOfBoundsException e) { // Should never occur + } catch (final StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); } types = new Type[vec.size()]; @@ -315,7 +315,7 @@ public abstract class Type { * @return array of corresponding Type objects */ public static Type[] getTypes( final java.lang.Class<?>[] classes ) { - Type[] ret = new Type[classes.length]; + final Type[] ret = new Type[classes.length]; for (int i = 0; i < ret.length; i++) { ret[i] = getType(classes[i]); } @@ -324,9 +324,9 @@ public abstract class Type { public static String getSignature( final java.lang.reflect.Method meth ) { - StringBuilder sb = new StringBuilder("("); - Class<?>[] params = meth.getParameterTypes(); // avoid clone - for (Class<?> param : params) { + final StringBuilder sb = new StringBuilder("("); + final Class<?>[] params = meth.getParameterTypes(); // avoid clone + for (final Class<?> param : params) { sb.append(getType(param).getSignature()); } sb.append(")"); @@ -355,18 +355,18 @@ public abstract class Type { } index = 1; // current string position while (signature.charAt(index) != ')') { - int coded = getTypeSize(signature.substring(index)); + final int coded = getTypeSize(signature.substring(index)); res += size(coded); index += consumed(coded); } - } catch (StringIndexOutOfBoundsException e) { // Should never occur + } catch (final StringIndexOutOfBoundsException e) { // Should never occur throw new ClassFormatException("Invalid method signature: " + signature, e); } return res; } static int getTypeSize( final String signature ) throws StringIndexOutOfBoundsException { - byte type = Utility.typeOfSignature(signature); + final byte type = Utility.typeOfSignature(signature); if (type <= Const.T_VOID) { return encode(BasicType.getType(type).getSize(), 1); } else if (type == Const.T_ARRAY) { @@ -375,10 +375,10 @@ public abstract class Type { dim++; } while (signature.charAt(dim) == '['); // Recurse, but just once, if the signature is ok - int consumed = consumed(getTypeSize(signature.substring(dim))); + final int consumed = consumed(getTypeSize(signature.substring(dim))); return encode(1, dim + consumed); } else { // type == T_REFERENCE - int index = signature.indexOf(';'); // Look for closing `;' + final int index = signature.indexOf(';'); // Look for closing `;' if (index < 0) { throw new ClassFormatException("Invalid signature: " + signature); } @@ -388,7 +388,7 @@ public abstract class Type { static int getReturnTypeSize(final String signature) { - int index = signature.lastIndexOf(')') + 1; + final int index = signature.lastIndexOf(')') + 1; return Type.size(getTypeSize(signature.substring(index))); } diff --git a/src/main/java/org/apache/bcel/util/AttributeHTML.java b/src/main/java/org/apache/bcel/util/AttributeHTML.java index a212828b..08863974 100644 --- a/src/main/java/org/apache/bcel/util/AttributeHTML.java +++ b/src/main/java/org/apache/bcel/util/AttributeHTML.java @@ -81,7 +81,7 @@ final class AttributeHTML { final void writeAttribute( final Attribute attribute, final String anchor, final int method_number ) { - byte tag = attribute.getTag(); + final byte tag = attribute.getTag(); int index; if (tag == Const.ATTR_UNKNOWN) { return; @@ -98,19 +98,19 @@ final class AttributeHTML { */ switch (tag) { case Const.ATTR_CODE: - Code c = (Code) attribute; + final Code c = (Code) attribute; // Some directly printable values file.print("<UL><LI>Maximum stack size = " + c.getMaxStack() + "</LI>\n<LI>Number of local variables = " + c.getMaxLocals() + "</LI>\n<LI><A HREF=\"" + class_name + "_code.html#method" + method_number + "\" TARGET=Code>Byte code</A></LI></UL>\n"); // Get handled exceptions and list them - CodeException[] ce = c.getExceptionTable(); - int len = ce.length; + final CodeException[] ce = c.getExceptionTable(); + final int len = ce.length; if (len > 0) { file.print("<P><B>Exceptions handled</B><UL>"); - for (CodeException cex : ce) { - int catch_type = cex.getCatchType(); // Index in constant pool + for (final CodeException cex : ce) { + final int catch_type = cex.getCatchType(); // Index in constant pool file.print("<LI>"); if (catch_type != 0) { file.print(constant_html.referenceConstant(catch_type)); // Create Link to _cp.html @@ -140,9 +140,9 @@ final class AttributeHTML { break; case Const.ATTR_EXCEPTIONS: // List thrown exceptions - int[] indices = ((ExceptionTable) attribute).getExceptionIndexTable(); + final int[] indices = ((ExceptionTable) attribute).getExceptionIndexTable(); file.print("<UL>"); - for (int indice : indices) { + for (final int indice : indices) { file.print("<LI><A HREF=\"" + class_name + "_cp.html#cp" + indice + "\" TARGET=\"ConstantPool\">Exception class index(" + indice + ")</A>\n"); @@ -150,7 +150,7 @@ final class AttributeHTML { file.print("</UL>\n"); break; case Const.ATTR_LINE_NUMBER_TABLE: - LineNumber[] line_numbers = ((LineNumberTable) attribute).getLineNumberTable(); + final LineNumber[] line_numbers = ((LineNumberTable) attribute).getLineNumberTable(); // List line number pairs file.print("<P>"); for (int i = 0; i < line_numbers.length; i++) { @@ -162,16 +162,16 @@ final class AttributeHTML { } break; case Const.ATTR_LOCAL_VARIABLE_TABLE: - LocalVariable[] vars = ((LocalVariableTable) attribute).getLocalVariableTable(); + final LocalVariable[] vars = ((LocalVariableTable) attribute).getLocalVariableTable(); // List name, range and type file.print("<UL>"); - for (LocalVariable var : vars) { + for (final LocalVariable var : vars) { index = var.getSignatureIndex(); String signature = ((ConstantUtf8) constant_pool.getConstant(index, Const.CONSTANT_Utf8)).getBytes(); signature = Utility.signatureToString(signature, false); - int start = var.getStartPC(); - int end = start + var.getLength(); + final int start = var.getStartPC(); + final int end = start + var.getLength(); file.println("<LI>" + Class2HTML.referenceType(signature) + " <B>" + var.getName() + "</B> in slot %" + var.getIndex() + "<BR>Valid from lines " + "<A HREF=\"" + class_name @@ -182,10 +182,10 @@ final class AttributeHTML { file.print("</UL>\n"); break; case Const.ATTR_INNER_CLASSES: - InnerClass[] classes = ((InnerClasses) attribute).getInnerClasses(); + final InnerClass[] classes = ((InnerClasses) attribute).getInnerClasses(); // List inner classes file.print("<UL>"); - for (InnerClass classe : classes) { + for (final InnerClass classe : classes) { String name; String access; index = classe.getInnerNameIndex(); diff --git a/src/main/java/org/apache/bcel/util/BCELFactory.java b/src/main/java/org/apache/bcel/util/BCELFactory.java index 8c4bd4fb..8c9549c3 100644 --- a/src/main/java/org/apache/bcel/util/BCELFactory.java +++ b/src/main/java/org/apache/bcel/util/BCELFactory.java @@ -84,7 +84,7 @@ class BCELFactory extends EmptyVisitor { if (!_mg.isAbstract() && !_mg.isNative()) { for (InstructionHandle ih = _mg.getInstructionList().getStart(); ih != null; ih = ih .getNext()) { - Instruction i = ih.getInstruction(); + final Instruction i = ih.getInstruction(); if (i instanceof BranchInstruction) { branch_map.put(i, ih); // memorize container } @@ -108,7 +108,7 @@ class BCELFactory extends EmptyVisitor { private boolean visitInstruction( final Instruction i ) { - short opcode = i.getOpcode(); + final short opcode = i.getOpcode(); if ((InstructionConst.getInstruction(opcode) != null) && !(i instanceof ConstantPushInstruction) && !(i instanceof ReturnInstruction)) { // Handled below _out.println("il.append(InstructionConst." @@ -121,13 +121,13 @@ class BCELFactory extends EmptyVisitor { @Override public void visitLocalVariableInstruction( final LocalVariableInstruction i ) { - short opcode = i.getOpcode(); - Type type = i.getType(_cp); + final short opcode = i.getOpcode(); + final Type type = i.getType(_cp); if (opcode == Const.IINC) { _out.println("il.append(new IINC(" + i.getIndex() + ", " + ((IINC) i).getIncrement() + "));"); } else { - String kind = (opcode < Const.ISTORE) ? "Load" : "Store"; + final String kind = (opcode < Const.ISTORE) ? "Load" : "Store"; _out.println("il.append(_factory.create" + kind + "(" + BCELifier.printType(type) + ", " + i.getIndex() + "));"); } @@ -136,9 +136,9 @@ class BCELFactory extends EmptyVisitor { @Override public void visitArrayInstruction( final ArrayInstruction i ) { - short opcode = i.getOpcode(); - Type type = i.getType(_cp); - String kind = (opcode < Const.IASTORE) ? "Load" : "Store"; + final short opcode = i.getOpcode(); + final Type type = i.getType(_cp); + final String kind = (opcode < Const.IASTORE) ? "Load" : "Store"; _out.println("il.append(_factory.createArray" + kind + "(" + BCELifier.printType(type) + "));"); } @@ -146,10 +146,10 @@ class BCELFactory extends EmptyVisitor { @Override public void visitFieldInstruction( final FieldInstruction i ) { - short opcode = i.getOpcode(); - String class_name = i.getClassName(_cp); - String field_name = i.getFieldName(_cp); - Type type = i.getFieldType(_cp); + final short opcode = i.getOpcode(); + final String class_name = i.getClassName(_cp); + final String field_name = i.getFieldName(_cp); + final Type type = i.getFieldType(_cp); _out.println("il.append(_factory.createFieldAccess(\"" + class_name + "\", \"" + field_name + "\", " + BCELifier.printType(type) + ", " + CONSTANT_PREFIX + Const.getOpcodeName(opcode).toUpperCase(Locale.ENGLISH) + "));"); @@ -158,11 +158,11 @@ class BCELFactory extends EmptyVisitor { @Override public void visitInvokeInstruction( final InvokeInstruction i ) { - short opcode = i.getOpcode(); - String class_name = i.getClassName(_cp); - String method_name = i.getMethodName(_cp); - Type type = i.getReturnType(_cp); - Type[] arg_types = i.getArgumentTypes(_cp); + final short opcode = i.getOpcode(); + final String class_name = i.getClassName(_cp); + final String method_name = i.getMethodName(_cp); + final Type type = i.getReturnType(_cp); + final Type[] arg_types = i.getArgumentTypes(_cp); _out.println("il.append(_factory.createInvoke(\"" + class_name + "\", \"" + method_name + "\", " + BCELifier.printType(type) + ", " + BCELifier.printArgumentTypes(arg_types) + ", " + CONSTANT_PREFIX @@ -178,7 +178,7 @@ class BCELFactory extends EmptyVisitor { } else { type = ((NEWARRAY) i).getType(); } - short opcode = ((Instruction) i).getOpcode(); + final short opcode = ((Instruction) i).getOpcode(); int dim = 1; switch (opcode) { case Const.NEW: @@ -213,7 +213,7 @@ class BCELFactory extends EmptyVisitor { } else if (value instanceof Long) { embed += "L"; } else if (value instanceof ObjectType) { - ObjectType ot = (ObjectType) value; + final ObjectType ot = (ObjectType) value; embed = "new ObjectType(\""+ot.getClassName()+"\")"; } @@ -241,21 +241,21 @@ class BCELFactory extends EmptyVisitor { @Override public void visitINSTANCEOF( final INSTANCEOF i ) { - Type type = i.getType(_cp); + final Type type = i.getType(_cp); _out.println("il.append(new INSTANCEOF(_cp.addClass(" + BCELifier.printType(type) + ")));"); } @Override public void visitCHECKCAST( final CHECKCAST i ) { - Type type = i.getType(_cp); + final Type type = i.getType(_cp); _out.println("il.append(_factory.createCheckCast(" + BCELifier.printType(type) + "));"); } @Override public void visitReturnInstruction( final ReturnInstruction i ) { - Type type = i.getType(_cp); + final Type type = i.getType(_cp); _out.println("il.append(_factory.createReturn(" + BCELifier.printType(type) + "));"); } @@ -265,14 +265,14 @@ class BCELFactory extends EmptyVisitor { @Override public void visitBranchInstruction( final BranchInstruction bi ) { - BranchHandle bh = (BranchHandle) branch_map.get(bi); - int pos = bh.getPosition(); - String name = bi.getName() + "_" + pos; + final BranchHandle bh = (BranchHandle) branch_map.get(bi); + final int pos = bh.getPosition(); + final String name = bi.getName() + "_" + pos; if (bi instanceof Select) { - Select s = (Select) bi; + final Select s = (Select) bi; branches.add(bi); - StringBuilder args = new StringBuilder("new int[] { "); - int[] matchs = s.getMatchs(); + final StringBuilder args = new StringBuilder("new int[] { "); + final int[] matchs = s.getMatchs(); for (int i = 0; i < matchs.length; i++) { args.append(matchs[i]); if (i < matchs.length - 1) { @@ -290,7 +290,7 @@ class BCELFactory extends EmptyVisitor { } _out.println(" }, null);"); } else { - int t_pos = bh.getTarget().getPosition(); + final int t_pos = bh.getTarget().getPosition(); String target; if (pos > t_pos) { target = "ih_" + t_pos; @@ -317,14 +317,14 @@ class BCELFactory extends EmptyVisitor { private void updateBranchTargets() { - for (BranchInstruction bi : branches) { - BranchHandle bh = (BranchHandle) branch_map.get(bi); - int pos = bh.getPosition(); - String name = bi.getName() + "_" + pos; + for (final BranchInstruction bi : branches) { + final BranchHandle bh = (BranchHandle) branch_map.get(bi); + final int pos = bh.getPosition(); + final String name = bi.getName() + "_" + pos; int t_pos = bh.getTarget().getPosition(); _out.println(" " + name + ".setTarget(ih_" + t_pos + ");"); if (bi instanceof Select) { - InstructionHandle[] ihs = ((Select) bi).getTargets(); + final InstructionHandle[] ihs = ((Select) bi).getTargets(); for (int j = 0; j < ihs.length; j++) { t_pos = ihs[j].getPosition(); _out.println(" " + name + ".setTarget(" + j + ", ih_" + t_pos + ");"); @@ -335,9 +335,9 @@ class BCELFactory extends EmptyVisitor { private void updateExceptionHandlers() { - CodeExceptionGen[] handlers = _mg.getExceptionHandlers(); - for (CodeExceptionGen h : handlers) { - String type = (h.getCatchType() == null) ? "null" : BCELifier.printType(h + final CodeExceptionGen[] handlers = _mg.getExceptionHandlers(); + for (final CodeExceptionGen h : handlers) { + final String type = (h.getCatchType() == null) ? "null" : BCELifier.printType(h .getCatchType()); _out.println(" method.addExceptionHandler(" + "ih_" + h.getStartPC().getPosition() + ", " + "ih_" + h.getEndPC().getPosition() + ", " + "ih_" diff --git a/src/main/java/org/apache/bcel/util/BCELifier.java b/src/main/java/org/apache/bcel/util/BCELifier.java index 50043acf..2022812c 100644 --- a/src/main/java/org/apache/bcel/util/BCELifier.java +++ b/src/main/java/org/apache/bcel/util/BCELifier.java @@ -85,9 +85,9 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { @Override public void visitJavaClass( final JavaClass clazz ) { String class_name = clazz.getClassName(); - String super_name = clazz.getSuperclassName(); - String package_name = clazz.getPackageName(); - String inter = Utility.printArray(clazz.getInterfaceNames(), false, true); + final String super_name = clazz.getSuperclassName(); + final String package_name = clazz.getPackageName(); + final String inter = Utility.printArray(clazz.getInterfaceNames(), false, true); if (!"".equals(package_name)) { class_name = class_name.substring(package_name.length() + 1); _out.println("package " + package_name + ";"); @@ -115,17 +115,17 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { _out.println(" }"); _out.println(); printCreate(); - Field[] fields = clazz.getFields(); + final Field[] fields = clazz.getFields(); if (fields.length > 0) { _out.println(" private void createFields() {"); _out.println(" FieldGen field;"); - for (Field field : fields) { + for (final Field field : fields) { field.accept(this); } _out.println(" }"); _out.println(); } - Method[] methods = clazz.getMethods(); + final Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { _out.println(" private void createMethod_" + i + "() {"); methods[i].accept(this); @@ -139,11 +139,11 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { private void printCreate() { _out.println(" public void create(OutputStream out) throws IOException {"); - Field[] fields = _clazz.getFields(); + final Field[] fields = _clazz.getFields(); if (fields.length > 0) { _out.println(" createFields();"); } - Method[] methods = _clazz.getMethods(); + final Method[] methods = _clazz.getMethods(); for (int i = 0; i < methods.length; i++) { _out.println(" createMethod_" + i + "();"); } @@ -154,7 +154,7 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { private void printMain() { - String class_name = _clazz.getClassName(); + final String class_name = _clazz.getClassName(); _out.println(" public static void main(String[] args) throws Exception {"); _out.println(" " + class_name + "Creator creator = new " + class_name + "Creator();"); _out.println(" creator.create(new FileOutputStream(\"" + class_name + ".class\"));"); @@ -167,9 +167,9 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { _out.println(); _out.println(" field = new FieldGen(" + printFlags(field.getAccessFlags()) + ", " + printType(field.getSignature()) + ", \"" + field.getName() + "\", _cp);"); - ConstantValue cv = field.getConstantValue(); + final ConstantValue cv = field.getConstantValue(); if (cv != null) { - String value = cv.toString(); + final String value = cv.toString(); _out.println(" field.setInitValue(" + value + ")"); } _out.println(" _cg.addField(field.getField());"); @@ -178,7 +178,7 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { @Override public void visitMethod( final Method method ) { - MethodGen mg = new MethodGen(method, _clazz.getClassName(), _cp); + final MethodGen mg = new MethodGen(method, _clazz.getClassName(), _cp); _out.println(" InstructionList il = new InstructionList();"); _out.println(" MethodGen method = new MethodGen(" + printFlags(method.getAccessFlags(), FLAGS.METHOD) + ", " @@ -187,7 +187,7 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { + "new String[] { " + Utility.printArray(mg.getArgumentNames(), false, true) + " }, \"" + method.getName() + "\", \"" + _clazz.getClassName() + "\", il, _cp);"); _out.println(); - BCELFactory factory = new BCELFactory(mg, _out); + final BCELFactory factory = new BCELFactory(mg, _out); factory.start(); _out.println(" method.setMaxStack();"); _out.println(" method.setMaxLocals();"); @@ -211,7 +211,7 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { if (flags == 0) { return "0"; } - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); for (int i = 0, pow = 1; pow <= Const.MAX_ACC_FLAG; i++) { if ((flags & pow) != 0) { if ((pow == Const.ACC_SYNCHRONIZED) && (location == FLAGS.CLASS)) { @@ -230,7 +230,7 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { } pow <<= 1; } - String str = buf.toString(); + final String str = buf.toString(); return str.substring(0, str.length() - 3); } @@ -239,7 +239,7 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { if (arg_types.length == 0) { return "Type.NO_ARGS"; } - StringBuilder args = new StringBuilder(); + final StringBuilder args = new StringBuilder(); for (int i = 0; i < arg_types.length; i++) { args.append(printType(arg_types[i])); if (i < arg_types.length - 1) { @@ -256,8 +256,8 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { static String printType( final String signature ) { - Type type = Type.getType(signature); - byte t = type.getType(); + final Type type = Type.getType(signature); + final byte t = type.getType(); if (t <= Const.T_VOID) { return "Type." + Const.getTypeName(t).toUpperCase(Locale.ENGLISH); } else if (type.toString().equals("java.lang.String")) { @@ -267,7 +267,7 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { } else if (type.toString().equals("java.lang.StringBuffer")) { return "Type.STRINGBUFFER"; } else if (type instanceof ArrayType) { - ArrayType at = (ArrayType) type; + final ArrayType at = (ArrayType) type; return "new ArrayType(" + printType(at.getBasicType()) + ", " + at.getDimensions() + ")"; } else { @@ -284,8 +284,8 @@ public class BCELifier extends org.apache.bcel.classfile.EmptyVisitor { System.out.println("\tThe class must exist on the classpath"); return; } - JavaClass java_class = getJavaClass(argv[0]); - BCELifier bcelifier = new BCELifier(java_class, System.out); + final JavaClass java_class = getJavaClass(argv[0]); + final BCELifier bcelifier = new BCELifier(java_class, System.out); bcelifier.start(); } diff --git a/src/main/java/org/apache/bcel/util/Class2HTML.java b/src/main/java/org/apache/bcel/util/Class2HTML.java index b01ee40b..47f167a1 100644 --- a/src/main/java/org/apache/bcel/util/Class2HTML.java +++ b/src/main/java/org/apache/bcel/util/Class2HTML.java @@ -82,24 +82,24 @@ public class Class2HTML implements Constants { * @param dir The directory to put the files in */ public Class2HTML(final JavaClass java_class, final String dir) throws IOException { - Method[] methods = java_class.getMethods(); + final Method[] methods = java_class.getMethods(); this.java_class = java_class; this.dir = dir; class_name = java_class.getClassName(); // Remember full name constant_pool = java_class.getConstantPool(); // Get package name by tacking off everything after the last `.' - int index = class_name.lastIndexOf('.'); + final int index = class_name.lastIndexOf('.'); if (index > -1) { class_package = class_name.substring(0, index); } else { class_package = ""; // default package } - ConstantHTML constant_html = new ConstantHTML(dir, class_name, class_package, methods, + final ConstantHTML constant_html = new ConstantHTML(dir, class_name, class_package, methods, constant_pool); /* Attributes can't be written in one step, so we just open a file * which will be written consequently. */ - AttributeHTML attribute_html = new AttributeHTML(dir, class_name, constant_pool, + final AttributeHTML attribute_html = new AttributeHTML(dir, class_name, constant_pool, constant_html); new MethodHTML(dir, class_name, methods, java_class.getFields(), constant_html, attribute_html); @@ -111,12 +111,12 @@ public class Class2HTML implements Constants { public static void main( final String[] argv ) throws IOException { - String[] file_name = new String[argv.length]; + final String[] file_name = new String[argv.length]; int files = 0; ClassParser parser = null; JavaClass java_class = null; String zip_file = null; - char sep = File.separatorChar; + final char sep = File.separatorChar; String dir = "." + sep; // Where to store HTML files /* Parse command line arguments. */ @@ -129,7 +129,7 @@ public class Class2HTML implements Constants { } final File store = new File(dir); if (!store.isDirectory()) { - boolean created = store.mkdirs(); // Create target directory if necessary + final boolean created = store.mkdirs(); // Create target directory if necessary if (!created) { if (!store.isDirectory()) { System.out.println("Tried to create the directory " + dir + " but failed"); @@ -179,7 +179,7 @@ public class Class2HTML implements Constants { static String referenceType( final String type ) { String short_type = Utility.compactClassName(type); short_type = Utility.compactClassName(short_type, class_package + ".", true); - int index = type.indexOf('['); // Type is an array? + final int index = type.indexOf('['); // Type is an array? String base_type = type; if (index > -1) { base_type = type.substring(0, index); // Tack of the `[' @@ -193,7 +193,7 @@ public class Class2HTML implements Constants { static String toHTML( final String str ) { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char ch; switch (ch = str.charAt(i)) { @@ -230,7 +230,7 @@ public class Class2HTML implements Constants { + "<FRAME NAME=\"Methods\" SRC=\"" + class_name + "_methods.html\"\n MARGINWIDTH=0 " + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n" + "</FRAMESET></FRAMESET></HTML>"); } - Attribute[] attributes = java_class.getAttributes(); + final Attribute[] attributes = java_class.getAttributes(); for (int i = 0; i < attributes.length; i++) { attribute_html.writeAttribute(attributes[i], "class" + i); } diff --git a/src/main/java/org/apache/bcel/util/ClassLoader.java b/src/main/java/org/apache/bcel/util/ClassLoader.java index d025944f..9411319e 100644 --- a/src/main/java/org/apache/bcel/util/ClassLoader.java +++ b/src/main/java/org/apache/bcel/util/ClassLoader.java @@ -111,7 +111,7 @@ public class ClassLoader extends java.lang.ClassLoader { /* Second try: Load system class using system class loader. You better * don't mess around with them. */ - for (String ignored_package : ignored_packages) { + for (final String ignored_package : ignored_packages) { if (class_name.startsWith(ignored_package)) { cl = getParent().loadClass(class_name); break; @@ -131,7 +131,7 @@ public class ClassLoader extends java.lang.ClassLoader { } } if (clazz != null) { - byte[] bytes = clazz.getBytes(); + final byte[] bytes = clazz.getBytes(); cl = defineClass(class_name, bytes, 0, bytes.length); } else { cl = Class.forName(class_name); @@ -169,22 +169,22 @@ public class ClassLoader extends java.lang.ClassLoader { * @param class_name compressed byte code with "$$BCEL$$" in it */ protected JavaClass createClass( final String class_name ) { - int index = class_name.indexOf(BCEL_TOKEN); - String real_name = class_name.substring(index + BCEL_TOKEN.length()); + final int index = class_name.indexOf(BCEL_TOKEN); + final String real_name = class_name.substring(index + BCEL_TOKEN.length()); JavaClass clazz = null; try { - byte[] bytes = Utility.decode(real_name, true); - ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "foo"); + final byte[] bytes = Utility.decode(real_name, true); + final ClassParser parser = new ClassParser(new ByteArrayInputStream(bytes), "foo"); clazz = parser.parse(); - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); return null; } // Adapt the class name to the passed value - ConstantPool cp = clazz.getConstantPool(); - ConstantClass cl = (ConstantClass) cp.getConstant(clazz.getClassNameIndex(), + final ConstantPool cp = clazz.getConstantPool(); + final ConstantClass cl = (ConstantClass) cp.getConstant(clazz.getClassNameIndex(), Constants.CONSTANT_Class); - ConstantUtf8 name = (ConstantUtf8) cp.getConstant(cl.getNameIndex(), + final ConstantUtf8 name = (ConstantUtf8) cp.getConstant(cl.getNameIndex(), Constants.CONSTANT_Utf8); name.setBytes(class_name.replace('.', '/')); return clazz; diff --git a/src/main/java/org/apache/bcel/util/ClassLoaderRepository.java b/src/main/java/org/apache/bcel/util/ClassLoaderRepository.java index 5ad10f87..fe2c8cf4 100644 --- a/src/main/java/org/apache/bcel/util/ClassLoaderRepository.java +++ b/src/main/java/org/apache/bcel/util/ClassLoaderRepository.java @@ -80,7 +80,7 @@ public class ClassLoaderRepository implements Repository { */ @Override public JavaClass loadClass(final String className) throws ClassNotFoundException { - String classFile = className.replace('.', '/'); + final String classFile = className.replace('.', '/'); JavaClass RC = findClass(className); if (RC != null) { return RC; @@ -89,11 +89,11 @@ public class ClassLoaderRepository implements Repository { if (is == null) { throw new ClassNotFoundException(className + " not found."); } - ClassParser parser = new ClassParser(is, className); + final ClassParser parser = new ClassParser(is, className); RC = parser.parse(); storeClass(RC); return RC; - } catch (IOException e) { + } catch (final IOException e) { throw new ClassNotFoundException(className + " not found: " + e, e); } } diff --git a/src/main/java/org/apache/bcel/util/ClassPath.java b/src/main/java/org/apache/bcel/util/ClassPath.java index 2f2f16de..de6d056e 100644 --- a/src/main/java/org/apache/bcel/util/ClassPath.java +++ b/src/main/java/org/apache/bcel/util/ClassPath.java @@ -69,11 +69,11 @@ public class ClassPath { */ public ClassPath(final String class_path) { this.class_path = class_path; - List<PathEntry> list = new ArrayList<>(); - for (StringTokenizer tok = new StringTokenizer(class_path, File.pathSeparator); tok.hasMoreTokens();) { - String path = tok.nextToken(); + final List<PathEntry> list = new ArrayList<>(); + for (final StringTokenizer tok = new StringTokenizer(class_path, File.pathSeparator); tok.hasMoreTokens();) { + final String path = tok.nextToken(); if (!path.isEmpty()) { - File file = new File(path); + final File file = new File(path); try { if (file.exists()) { if (file.isDirectory()) { @@ -82,7 +82,7 @@ public class ClassPath { list.add(new Zip(new ZipFile(file))); } } - } catch (IOException e) { + } catch (final IOException e) { if (path.endsWith(".zip") || path.endsWith(".jar")) { System.err.println("CLASSPATH component " + file + ": " + e); } @@ -124,7 +124,7 @@ public class ClassPath { @Override public boolean equals( final Object o ) { if (o instanceof ClassPath) { - ClassPath cp = (ClassPath)o; + final ClassPath cp = (ClassPath)o; return class_path.equals(cp.toString()); } return false; @@ -133,10 +133,10 @@ public class ClassPath { private static void getPathComponents( final String path, final List<String> list ) { if (path != null) { - StringTokenizer tok = new StringTokenizer(path, File.pathSeparator); + final StringTokenizer tok = new StringTokenizer(path, File.pathSeparator); while (tok.hasMoreTokens()) { - String name = tok.nextToken(); - File file = new File(name); + final String name = tok.nextToken(); + final File file = new File(name); if (file.exists()) { list.add(name); } @@ -152,26 +152,26 @@ public class ClassPath { */ // @since 6.0 no longer final public static String getClassPath() { - String class_path = System.getProperty("java.class.path"); - String boot_path = System.getProperty("sun.boot.class.path"); - String ext_path = System.getProperty("java.ext.dirs"); - List<String> list = new ArrayList<>(); + final String class_path = System.getProperty("java.class.path"); + final String boot_path = System.getProperty("sun.boot.class.path"); + final String ext_path = System.getProperty("java.ext.dirs"); + final List<String> list = new ArrayList<>(); getPathComponents(class_path, list); getPathComponents(boot_path, list); - List<String> dirs = new ArrayList<>(); + final List<String> dirs = new ArrayList<>(); getPathComponents(ext_path, dirs); - for (String d : dirs) { - File ext_dir = new File(d); - String[] extensions = ext_dir.list(ARCHIVE_FILTER); + for (final String d : dirs) { + final File ext_dir = new File(d); + final String[] extensions = ext_dir.list(ARCHIVE_FILTER); if (extensions != null) { - for (String extension : extensions) { + for (final String extension : extensions) { list.add(ext_dir.getPath() + File.separatorChar + extension); } } } - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); String separator = ""; - for (String path : list) { + for (final String path : list) { buf.append(separator); separator = File.pathSeparator; buf.append(path); @@ -200,7 +200,7 @@ public class ClassPath { InputStream is = null; try { is = getClass().getClassLoader().getResourceAsStream(name + suffix); // may return null - } catch (Exception e) { + } catch (final Exception e) { // ignored } if (is != null) { @@ -215,7 +215,7 @@ public class ClassPath { * @since 6.0 */ public InputStream getResourceAsStream(final String name) { - for (PathEntry path : paths) { + for (final PathEntry path : paths) { InputStream is; if ((is = path.getResourceAsStream(name)) != null) { return is; @@ -230,7 +230,7 @@ public class ClassPath { * @since 6.0 */ public URL getResource(final String name) { - for (PathEntry path : paths) { + for (final PathEntry path : paths) { URL url; if ((url = path.getResource(name)) != null) { return url; @@ -246,8 +246,8 @@ public class ClassPath { * @since 6.0 */ public Enumeration<URL> getResources(final String name) { - Vector<URL> results = new Vector<>(); - for (PathEntry path : paths) { + final Vector<URL> results = new Vector<>(); + for (final PathEntry path : paths) { URL url; if ((url = path.getResource(name)) != null) { results.add(url); @@ -281,8 +281,8 @@ public class ClassPath { private ClassFile getClassFileInternal(final String name, final String suffix) throws IOException { - for (PathEntry path : paths) { - ClassFile cf = path.getClassFile(name, suffix); + for (final PathEntry path : paths) { + final ClassFile cf = path.getClassFile(name, suffix); if(cf != null) { return cf; @@ -314,7 +314,7 @@ public class ClassPath { throw new IOException("Couldn't find: " + name + suffix); } dis = new DataInputStream(is); - byte[] bytes = new byte[is.available()]; + final byte[] bytes = new byte[is.available()]; dis.readFully(bytes); return bytes; } finally { @@ -338,7 +338,7 @@ public class ClassPath { * @return full (canonical) path for file */ public String getPath( String name ) throws IOException { - int index = name.lastIndexOf('.'); + final int index = name.lastIndexOf('.'); String suffix = ""; if (index > 0) { suffix = name.substring(index); @@ -409,7 +409,7 @@ public class ClassPath { final File file = new File(dir + File.separatorChar + name.replace('/', File.separatorChar)); try { return file.exists() ? file.toURI().toURL() : null; - } catch (MalformedURLException e) { + } catch (final MalformedURLException e) { return null; } } @@ -420,7 +420,7 @@ public class ClassPath { final File file = new File(dir + File.separatorChar + name.replace('/', File.separatorChar)); try { return file.exists() ? new FileInputStream(file) : null; - } catch (IOException e) { + } catch (final IOException e) { return null; } } @@ -441,7 +441,7 @@ public class ClassPath { public String getPath() { try { return file.getCanonicalPath(); - } catch (IOException e) { + } catch (final IOException e) { return null; } } @@ -487,7 +487,7 @@ public class ClassPath { final ZipEntry entry = zip.getEntry(name); try { return (entry != null) ? new URL("jar:file:" + zip.getName() + "!/" + name) : null; - } catch (MalformedURLException e) { + } catch (final MalformedURLException e) { return null; } } @@ -497,7 +497,7 @@ public class ClassPath { final ZipEntry entry = zip.getEntry(name); try { return (entry != null) ? zip.getInputStream(entry) : null; - } catch (IOException e) { + } catch (final IOException e) { return null; } } diff --git a/src/main/java/org/apache/bcel/util/ClassPathRepository.java b/src/main/java/org/apache/bcel/util/ClassPathRepository.java index dcc23051..f58d1b11 100644 --- a/src/main/java/org/apache/bcel/util/ClassPathRepository.java +++ b/src/main/java/org/apache/bcel/util/ClassPathRepository.java @@ -81,13 +81,13 @@ public class ClassPathRepository implements Repository { throw new IllegalArgumentException("Invalid class name " + className); } className = className.replace('/', '.'); // Just in case, canonical form - JavaClass clazz = findClass(className); + final JavaClass clazz = findClass(className); if (clazz != null) { return clazz; } try { return loadClass(_path.getInputStream(className), className); - } catch (IOException e) { + } catch (final IOException e) { throw new ClassNotFoundException("Exception while looking for class " + className + ": " + e, e); } } @@ -106,20 +106,20 @@ public class ClassPathRepository implements Repository { */ @Override public JavaClass loadClass(final Class<?> clazz) throws ClassNotFoundException { - String className = clazz.getName(); - JavaClass repositoryClass = findClass(className); + final String className = clazz.getName(); + final JavaClass repositoryClass = findClass(className); if (repositoryClass != null) { return repositoryClass; } String name = className; - int i = name.lastIndexOf('.'); + final int i = name.lastIndexOf('.'); if (i > 0) { name = name.substring(i + 1); } JavaClass cls = null; try (InputStream clsStream = clazz.getResourceAsStream(name + ".class")) { return cls = loadClass(clsStream, className); - } catch (IOException e) { + } catch (final IOException e) { return cls; } } @@ -127,18 +127,18 @@ public class ClassPathRepository implements Repository { private JavaClass loadClass(final InputStream is, final String className) throws ClassNotFoundException { try { if (is != null) { - ClassParser parser = new ClassParser(is, className); - JavaClass clazz = parser.parse(); + final ClassParser parser = new ClassParser(is, className); + final JavaClass clazz = parser.parse(); storeClass(clazz); return clazz; } - } catch (IOException e) { + } catch (final IOException e) { throw new ClassNotFoundException("Exception while looking for class " + className + ": " + e, e); } finally { if (is != null) { try { is.close(); - } catch (IOException e) { + } catch (final IOException e) { // ignored } } diff --git a/src/main/java/org/apache/bcel/util/ClassSet.java b/src/main/java/org/apache/bcel/util/ClassSet.java index 9dcb33be..b4f08248 100644 --- a/src/main/java/org/apache/bcel/util/ClassSet.java +++ b/src/main/java/org/apache/bcel/util/ClassSet.java @@ -57,8 +57,8 @@ public class ClassSet { public JavaClass[] toArray() { - Collection<JavaClass> values = map.values(); - JavaClass[] classes = new JavaClass[values.size()]; + final Collection<JavaClass> values = map.values(); + final JavaClass[] classes = new JavaClass[values.size()]; values.toArray(classes); return classes; } diff --git a/src/main/java/org/apache/bcel/util/ClassVector.java b/src/main/java/org/apache/bcel/util/ClassVector.java index aba82554..c8dc3454 100644 --- a/src/main/java/org/apache/bcel/util/ClassVector.java +++ b/src/main/java/org/apache/bcel/util/ClassVector.java @@ -54,7 +54,7 @@ public class ClassVector implements java.io.Serializable { public JavaClass[] toArray() { - JavaClass[] classes = new JavaClass[vec.size()]; + final JavaClass[] classes = new JavaClass[vec.size()]; vec.toArray(classes); return classes; } diff --git a/src/main/java/org/apache/bcel/util/CodeHTML.java b/src/main/java/org/apache/bcel/util/CodeHTML.java index 32f16dfe..395ef28a 100644 --- a/src/main/java/org/apache/bcel/util/CodeHTML.java +++ b/src/main/java/org/apache/bcel/util/CodeHTML.java @@ -78,7 +78,7 @@ final class CodeHTML { * @return String representation of byte code */ private String codeToHTML( final ByteSequence bytes, final int method_number ) throws IOException { - short opcode = (short) bytes.readUnsignedByte(); + final short opcode = (short) bytes.readUnsignedByte(); String name; String signature; int default_offset = 0; @@ -91,13 +91,13 @@ final class CodeHTML { int[] jump_table; int no_pad_bytes = 0; int offset; - StringBuilder buf = new StringBuilder(256); // CHECKSTYLE IGNORE MagicNumber + final StringBuilder buf = new StringBuilder(256); // CHECKSTYLE IGNORE MagicNumber buf.append("<TT>").append(Const.getOpcodeName(opcode)).append("</TT></TD><TD>"); /* Special case: Skip (0-3) padding bytes, i.e., the * following bytes are 4-byte-aligned */ if ((opcode == Const.TABLESWITCH) || (opcode == Const.LOOKUPSWITCH)) { - int remainder = bytes.getIndex() % 4; + final int remainder = bytes.getIndex() % 4; no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder; for (int i = 0; i < no_pad_bytes; i++) { bytes.readByte(); @@ -120,7 +120,7 @@ final class CodeHTML { } buf.append("<TH>default</TH></TR>\n<TR>"); // Print target and default indices in second row - for (int element : jump_table) { + for (final int element : jump_table) { buf.append("<TD><A HREF=\"#code").append(method_number).append("@").append( element).append("\">").append(element).append("</A></TD>"); } @@ -131,14 +131,14 @@ final class CodeHTML { /* Lookup switch has variable length arguments. */ case Const.LOOKUPSWITCH: - int npairs = bytes.readInt(); + final int npairs = bytes.readInt(); offset = bytes.getIndex() - 8 - no_pad_bytes - 1; jump_table = new int[npairs]; default_offset += offset; buf.append("<TABLE BORDER=1><TR>"); // Print switch indices in first row (and default) for (int i = 0; i < npairs; i++) { - int match = bytes.readInt(); + final int match = bytes.readInt(); jump_table[i] = offset + bytes.readInt(); buf.append("<TH>").append(match).append("</TH>"); } @@ -181,7 +181,7 @@ final class CodeHTML { */ case Const.GOTO_W: case Const.JSR_W: - int windex = bytes.getIndex() + bytes.readInt() - 1; + final int windex = bytes.getIndex() + bytes.readInt() - 1; buf.append("<A HREF=\"#code").append(method_number).append("@").append(windex) .append("\">").append(windex).append("</A>"); break; @@ -228,13 +228,13 @@ final class CodeHTML { case Const.PUTFIELD: case Const.PUTSTATIC: index = bytes.readShort(); - ConstantFieldref c1 = (ConstantFieldref) constant_pool.getConstant(index, + final ConstantFieldref c1 = (ConstantFieldref) constant_pool.getConstant(index, Const.CONSTANT_Fieldref); class_index = c1.getClassIndex(); name = constant_pool.getConstantString(class_index, Const.CONSTANT_Class); name = Utility.compactClassName(name, false); index = c1.getNameAndTypeIndex(); - String field_name = constant_pool.constantToString(index, Const.CONSTANT_NameAndType); + final String field_name = constant_pool.constantToString(index, Const.CONSTANT_NameAndType); if (name.equals(class_name)) { // Local field buf.append("<A HREF=\"").append(class_name).append("_methods.html#field") .append(field_name).append("\" TARGET=Methods>").append(field_name) @@ -259,14 +259,14 @@ final class CodeHTML { case Const.INVOKEVIRTUAL: case Const.INVOKEINTERFACE: case Const.INVOKEDYNAMIC: - int m_index = bytes.readShort(); + final int m_index = bytes.readShort(); String str; if (opcode == Const.INVOKEINTERFACE) { // Special treatment needed bytes.readUnsignedByte(); // Redundant bytes.readUnsignedByte(); // Reserved // int nargs = bytes.readUnsignedByte(); // Redundant // int reserved = bytes.readUnsignedByte(); // Reserved - ConstantInterfaceMethodref c = (ConstantInterfaceMethodref) constant_pool + final ConstantInterfaceMethodref c = (ConstantInterfaceMethodref) constant_pool .getConstant(m_index, Const.CONSTANT_InterfaceMethodref); class_index = c.getClassIndex(); index = c.getNameAndTypeIndex(); @@ -274,7 +274,7 @@ final class CodeHTML { } else if (opcode == Const.INVOKEDYNAMIC) { // Special treatment needed bytes.readUnsignedByte(); // Reserved bytes.readUnsignedByte(); // Reserved - ConstantInvokeDynamic c = (ConstantInvokeDynamic) constant_pool + final ConstantInvokeDynamic c = (ConstantInvokeDynamic) constant_pool .getConstant(m_index, Const.CONSTANT_InvokeDynamic); index = c.getNameAndTypeIndex(); name = "#" + c.getBootstrapMethodAttrIndex(); @@ -282,7 +282,7 @@ final class CodeHTML { // UNDONE: Java8 now allows INVOKESPECIAL and INVOKESTATIC to // reference EITHER a Methodref OR an InterfaceMethodref. // Not sure if that affects this code or not. (markro) - ConstantMethodref c = (ConstantMethodref) constant_pool.getConstant(m_index, + final ConstantMethodref c = (ConstantMethodref) constant_pool.getConstant(m_index, Const.CONSTANT_Methodref); class_index = c.getClassIndex(); index = c.getNameAndTypeIndex(); @@ -291,11 +291,11 @@ final class CodeHTML { str = Class2HTML.toHTML(constant_pool.constantToString(constant_pool.getConstant( index, Const.CONSTANT_NameAndType))); // Get signature, i.e., types - ConstantNameAndType c2 = (ConstantNameAndType) constant_pool.getConstant(index, + final ConstantNameAndType c2 = (ConstantNameAndType) constant_pool.getConstant(index, Const.CONSTANT_NameAndType); signature = constant_pool.constantToString(c2.getSignatureIndex(), Const.CONSTANT_Utf8); - String[] args = Utility.methodSignatureArgumentTypes(signature, false); - String type = Utility.methodSignatureReturnType(signature, false); + final String[] args = Utility.methodSignatureArgumentTypes(signature, false); + final String type = Utility.methodSignatureReturnType(signature, false); buf.append(name).append(".<A HREF=\"").append(class_name).append("_cp.html#cp") .append(m_index).append("\" TARGET=ConstantPool>").append(str).append( "</A>").append("("); @@ -336,7 +336,7 @@ final class CodeHTML { */ case Const.MULTIANEWARRAY: index = bytes.readShort(); - int dimensions = bytes.readByte(); + final int dimensions = bytes.readByte(); buf.append(constant_html.referenceConstant(index)).append(":").append(dimensions) .append("-dimensional"); break; @@ -390,21 +390,21 @@ final class CodeHTML { * (try .. catch) in this method. We only need the line number here. */ if (code != null) { - CodeException[] ce = code.getExceptionTable(); - for (CodeException cex : ce) { + final CodeException[] ce = code.getExceptionTable(); + for (final CodeException cex : ce) { goto_set.set(cex.getStartPC()); goto_set.set(cex.getEndPC()); goto_set.set(cex.getHandlerPC()); } // Look for local variables and their range - Attribute[] attributes = code.getAttributes(); - for (Attribute attribute : attributes) { + final Attribute[] attributes = code.getAttributes(); + for (final Attribute attribute : attributes) { if (attribute.getTag() == Const.ATTR_LOCAL_VARIABLE_TABLE) { - LocalVariable[] vars = ((LocalVariableTable) attribute) + final LocalVariable[] vars = ((LocalVariableTable) attribute) .getLocalVariableTable(); - for (LocalVariable var : vars) { - int start = var.getStartPC(); - int end = start + var.getLength(); + for (final LocalVariable var : vars) { + final int start = var.getStartPC(); + final int end = start + var.getLength(); goto_set.set(start); goto_set.set(end); } @@ -420,8 +420,8 @@ final class CodeHTML { case Const.TABLESWITCH: case Const.LOOKUPSWITCH: //bytes.readByte(); // Skip already read byte - int remainder = bytes.getIndex() % 4; - int no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder; + final int remainder = bytes.getIndex() % 4; + final int no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder; int default_offset; int offset; for (int j = 0; j < no_pad_bytes; j++) { @@ -430,8 +430,8 @@ final class CodeHTML { // Both cases have a field default_offset in common default_offset = bytes.readInt(); if (opcode == Const.TABLESWITCH) { - int low = bytes.readInt(); - int high = bytes.readInt(); + final int low = bytes.readInt(); + final int high = bytes.readInt(); offset = bytes.getIndex() - 12 - no_pad_bytes - 1; default_offset += offset; goto_set.set(default_offset); @@ -440,7 +440,7 @@ final class CodeHTML { goto_set.set(index); } } else { // LOOKUPSWITCH - int npairs = bytes.readInt(); + final int npairs = bytes.readInt(); offset = bytes.getIndex() - 8 - no_pad_bytes - 1; default_offset += offset; goto_set.set(default_offset); @@ -493,19 +493,19 @@ final class CodeHTML { */ private void writeMethod( final Method method, final int method_number ) throws IOException { // Get raw signature - String signature = method.getSignature(); + final String signature = method.getSignature(); // Get array of strings containing the argument types - String[] args = Utility.methodSignatureArgumentTypes(signature, false); + final String[] args = Utility.methodSignatureArgumentTypes(signature, false); // Get return type string - String type = Utility.methodSignatureReturnType(signature, false); + final String type = Utility.methodSignatureReturnType(signature, false); // Get method name - String name = method.getName(); - String html_name = Class2HTML.toHTML(name); + final String name = method.getName(); + final String html_name = Class2HTML.toHTML(name); // Get method's access flags String access = Utility.accessToString(method.getAccessFlags()); access = Utility.replace(access, " ", " "); // Get the method's attributes, the Code Attribute in particular - Attribute[] attributes = method.getAttributes(); + final Attribute[] attributes = method.getAttributes(); file.print("<P><B><FONT COLOR=\"#FF0000\">" + access + "</FONT> " + "<A NAME=method" + method_number + ">" + Class2HTML.referenceType(type) + "</A> <A HREF=\"" + class_name + "_methods.html#method" + method_number + "\" TARGET=Methods>" @@ -532,7 +532,7 @@ final class CodeHTML { } if (tag == Const.ATTR_CODE) { c = (Code) attributes[i]; - Attribute[] attributes2 = c.getAttributes(); + final Attribute[] attributes2 = c.getAttributes(); code = c.getCode(); file.print("<UL>"); for (int j = 0; j < attributes2.length; j++) { @@ -556,8 +556,8 @@ final class CodeHTML { file.println("<TABLE BORDER=0><TR><TH ALIGN=LEFT>Byte<BR>offset</TH>" + "<TH ALIGN=LEFT>Instruction</TH><TH ALIGN=LEFT>Argument</TH>"); for (; stream.available() > 0;) { - int offset = stream.getIndex(); - String str = codeToHTML(stream, method_number); + final int offset = stream.getIndex(); + final String str = codeToHTML(stream, method_number); String anchor = ""; /* * Set an anchor mark if this line is targetted by a goto, jsr, etc. Defining an anchor for every diff --git a/src/main/java/org/apache/bcel/util/ConstantHTML.java b/src/main/java/org/apache/bcel/util/ConstantHTML.java index 546b343c..174842e3 100644 --- a/src/main/java/org/apache/bcel/util/ConstantHTML.java +++ b/src/main/java/org/apache/bcel/util/ConstantHTML.java @@ -84,7 +84,7 @@ final class ConstantHTML { private void writeConstant( final int index ) { - byte tag = constants[index].getTag(); + final byte tag = constants[index].getTag(); int class_index; int name_index; String ref; @@ -98,36 +98,36 @@ final class ConstantHTML { case Const.CONSTANT_Methodref: // Get class_index and name_and_type_index, depending on type if (tag == Const.CONSTANT_Methodref) { - ConstantMethodref c = (ConstantMethodref) constant_pool.getConstant(index, + final ConstantMethodref c = (ConstantMethodref) constant_pool.getConstant(index, Const.CONSTANT_Methodref); class_index = c.getClassIndex(); name_index = c.getNameAndTypeIndex(); } else { - ConstantInterfaceMethodref c1 = (ConstantInterfaceMethodref) constant_pool + final ConstantInterfaceMethodref c1 = (ConstantInterfaceMethodref) constant_pool .getConstant(index, Const.CONSTANT_InterfaceMethodref); class_index = c1.getClassIndex(); name_index = c1.getNameAndTypeIndex(); } // Get method name and its class - String method_name = constant_pool.constantToString(name_index, + final String method_name = constant_pool.constantToString(name_index, Const.CONSTANT_NameAndType); - String html_method_name = Class2HTML.toHTML(method_name); + final String html_method_name = Class2HTML.toHTML(method_name); // Partially compacted class name, i.e., / -> . - String method_class = constant_pool.constantToString(class_index, Const.CONSTANT_Class); + final String method_class = constant_pool.constantToString(class_index, Const.CONSTANT_Class); String short_method_class = Utility.compactClassName(method_class); // I.e., remove java.lang. short_method_class = Utility.compactClassName(short_method_class, class_package + ".", true); // Remove class package prefix // Get method signature - ConstantNameAndType c2 = (ConstantNameAndType) constant_pool.getConstant( + final ConstantNameAndType c2 = (ConstantNameAndType) constant_pool.getConstant( name_index, Const.CONSTANT_NameAndType); - String signature = constant_pool.constantToString(c2.getSignatureIndex(), + final String signature = constant_pool.constantToString(c2.getSignatureIndex(), Const.CONSTANT_Utf8); // Get array of strings containing the argument types - String[] args = Utility.methodSignatureArgumentTypes(signature, false); + final String[] args = Utility.methodSignatureArgumentTypes(signature, false); // Get return type string - String type = Utility.methodSignatureReturnType(signature, false); - String ret_type = Class2HTML.referenceType(type); - StringBuilder buf = new StringBuilder("("); + final String type = Utility.methodSignatureReturnType(signature, false); + final String ret_type = Class2HTML.referenceType(type); + final StringBuilder buf = new StringBuilder("("); for (int i = 0; i < args.length; i++) { buf.append(Class2HTML.referenceType(args[i])); if (i < args.length - 1) { @@ -135,7 +135,7 @@ final class ConstantHTML { } } buf.append(")"); - String arg_types = buf.toString(); + final String arg_types = buf.toString(); if (method_class.equals(class_name)) { ref = "<A HREF=\"" + class_name + "_code.html#method" + getMethodNumber(method_name + signature) + "\" TARGET=Code>" @@ -155,16 +155,16 @@ final class ConstantHTML { break; case Const.CONSTANT_Fieldref: // Get class_index and name_and_type_index - ConstantFieldref c3 = (ConstantFieldref) constant_pool.getConstant(index, + final ConstantFieldref c3 = (ConstantFieldref) constant_pool.getConstant(index, Const.CONSTANT_Fieldref); class_index = c3.getClassIndex(); name_index = c3.getNameAndTypeIndex(); // Get method name and its class (compacted) - String field_class = constant_pool.constantToString(class_index, Const.CONSTANT_Class); + final String field_class = constant_pool.constantToString(class_index, Const.CONSTANT_Class); String short_field_class = Utility.compactClassName(field_class); // I.e., remove java.lang. short_field_class = Utility.compactClassName(short_field_class, class_package + ".", true); // Remove class package prefix - String field_name = constant_pool + final String field_name = constant_pool .constantToString(name_index, Const.CONSTANT_NameAndType); if (field_class.equals(class_name)) { ref = "<A HREF=\"" + field_class + "_methods.html#field" + field_name @@ -183,9 +183,9 @@ final class ConstantHTML { + ")</A></UL>"); break; case Const.CONSTANT_Class: - ConstantClass c4 = (ConstantClass) constant_pool.getConstant(index, Const.CONSTANT_Class); + final ConstantClass c4 = (ConstantClass) constant_pool.getConstant(index, Const.CONSTANT_Class); name_index = c4.getNameIndex(); - String class_name2 = constant_pool.constantToString(index, tag); // / -> . + final String class_name2 = constant_pool.constantToString(index, tag); // / -> . String short_class_name = Utility.compactClassName(class_name2); // I.e., remove java.lang. short_class_name = Utility.compactClassName(short_class_name, class_package + ".", true); // Remove class package prefix @@ -197,18 +197,18 @@ final class ConstantHTML { + "\">Name index(" + name_index + ")</A></UL>\n"); break; case Const.CONSTANT_String: - ConstantString c5 = (ConstantString) constant_pool.getConstant(index, + final ConstantString c5 = (ConstantString) constant_pool.getConstant(index, Const.CONSTANT_String); name_index = c5.getStringIndex(); - String str = Class2HTML.toHTML(constant_pool.constantToString(index, tag)); + final String str = Class2HTML.toHTML(constant_pool.constantToString(index, tag)); file.println("<P><TT>" + str + "</TT><UL>" + "<LI><A HREF=\"#cp" + name_index + "\">Name index(" + name_index + ")</A></UL>\n"); break; case Const.CONSTANT_NameAndType: - ConstantNameAndType c6 = (ConstantNameAndType) constant_pool.getConstant(index, + final ConstantNameAndType c6 = (ConstantNameAndType) constant_pool.getConstant(index, Const.CONSTANT_NameAndType); name_index = c6.getNameIndex(); - int signature_index = c6.getSignatureIndex(); + final int signature_index = c6.getSignatureIndex(); file.println("<P><TT>" + Class2HTML.toHTML(constant_pool.constantToString(index, tag)) + "</TT><UL>" + "<LI><A HREF=\"#cp" + name_index + "\">Name index(" @@ -223,7 +223,7 @@ final class ConstantHTML { private int getMethodNumber( final String str ) { for (int i = 0; i < methods.length; i++) { - String cmp = methods[i].getName() + methods[i].getSignature(); + final String cmp = methods[i].getName() + methods[i].getSignature(); if (cmp.equals(str)) { return i; } diff --git a/src/main/java/org/apache/bcel/util/InstructionFinder.java b/src/main/java/org/apache/bcel/util/InstructionFinder.java index 0596e1df..fc7bfd3e 100644 --- a/src/main/java/org/apache/bcel/util/InstructionFinder.java +++ b/src/main/java/org/apache/bcel/util/InstructionFinder.java @@ -90,8 +90,8 @@ public class InstructionFinder { * match. */ public final void reread() { - int size = il.getLength(); - char[] buf = new char[size]; // Create a string with length equal to il length + final int size = il.getLength(); + final char[] buf = new char[size]; // Create a string with length equal to il length handles = il.getInstructionHandles(); // Map opcodes to characters for (int i = 0; i < size; i++) { @@ -109,7 +109,7 @@ public class InstructionFinder { * @return encoded string for a pattern such as "BranchInstruction". */ private static String mapName( final String pattern ) { - String result = map.get(pattern); + final String result = map.get(pattern); if (result != null) { return result; } @@ -133,13 +133,13 @@ public class InstructionFinder { */ private static String compilePattern( final String pattern ) { //Bug: BCEL-77 - Instructions are assumed to be english, to avoid odd Locale issues - String lower = pattern.toLowerCase(Locale.ENGLISH); - StringBuilder buf = new StringBuilder(); - int size = pattern.length(); + final String lower = pattern.toLowerCase(Locale.ENGLISH); + final StringBuilder buf = new StringBuilder(); + final int size = pattern.length(); for (int i = 0; i < size; i++) { char ch = lower.charAt(i); if (Character.isLetterOrDigit(ch)) { - StringBuilder name = new StringBuilder(); + final StringBuilder name = new StringBuilder(); while ((Character.isLetterOrDigit(ch) || ch == '_') && i < size) { name.append(ch); if (++i < size) { @@ -162,7 +162,7 @@ public class InstructionFinder { * @return the matched piece of code as an array of instruction (handles) */ private InstructionHandle[] getMatch( final int matched_from, final int match_length ) { - InstructionHandle[] match = new InstructionHandle[match_length]; + final InstructionHandle[] match = new InstructionHandle[match_length]; System.arraycopy(handles, matched_from, match, 0, match_length); return match; } @@ -204,7 +204,7 @@ public class InstructionFinder { * instruction handles describing the matched area */ public final Iterator<InstructionHandle[]> search( final String pattern, final InstructionHandle from, final CodeConstraint constraint ) { - String search = compilePattern(pattern); + final String search = compilePattern(pattern); int start = -1; for (int i = 0; i < handles.length; i++) { if (handles[i] == from) { @@ -216,14 +216,14 @@ public class InstructionFinder { throw new ClassGenException("Instruction handle " + from + " not found in instruction list."); } - Pattern regex = Pattern.compile(search); - List<InstructionHandle[]> matches = new ArrayList<>(); - Matcher matcher = regex.matcher(il_string); + final Pattern regex = Pattern.compile(search); + final List<InstructionHandle[]> matches = new ArrayList<>(); + final Matcher matcher = regex.matcher(il_string); while (start < il_string.length() && matcher.find(start)) { - int startExpr = matcher.start(); - int endExpr = matcher.end(); - int lenExpr = endExpr - startExpr; - InstructionHandle[] match = getMatch(startExpr, lenExpr); + final int startExpr = matcher.start(); + final int endExpr = matcher.end(); + final int lenExpr = endExpr - startExpr; + final InstructionHandle[] match = getMatch(startExpr, lenExpr); if ((constraint == null) || constraint.checkCode(match)) { matches.add(match); } @@ -358,16 +358,16 @@ public class InstructionFinder { map.put("fstore", precompile(Const.FSTORE_0, Const.FSTORE_3, Const.FSTORE)); map.put("astore", precompile(Const.ASTORE_0, Const.ASTORE_3, Const.ASTORE)); // Compile strings - for (Map.Entry<String, String> entry : map.entrySet()) { - String key = entry.getKey(); - String value = entry.getValue(); - char ch = value.charAt(1); // Omit already precompiled patterns + for (final Map.Entry<String, String> entry : map.entrySet()) { + final String key = entry.getKey(); + final String value = entry.getValue(); + final char ch = value.charAt(1); // Omit already precompiled patterns if (ch < OFFSET) { map.put(key, compilePattern(value)); // precompile all patterns } } // Add instruction alias to match anything - StringBuilder buf = new StringBuilder("("); + final StringBuilder buf = new StringBuilder("("); for (short i = 0; i < NO_OPCODES; i++) { if (Const.getNoOfOperands(i) != Const.UNDEFINED) { // Not an invalid opcode buf.append(makeChar(i)); @@ -382,7 +382,7 @@ public class InstructionFinder { private static String precompile( final short from, final short to, final short extra ) { - StringBuilder buf = new StringBuilder("("); + final StringBuilder buf = new StringBuilder("("); for (short i = from; i <= to; i++) { buf.append(makeChar(i)); buf.append('|'); diff --git a/src/main/java/org/apache/bcel/util/JavaWrapper.java b/src/main/java/org/apache/bcel/util/JavaWrapper.java index 4aed9716..fdcb8815 100644 --- a/src/main/java/org/apache/bcel/util/JavaWrapper.java +++ b/src/main/java/org/apache/bcel/util/JavaWrapper.java @@ -40,13 +40,13 @@ public class JavaWrapper { private static java.lang.ClassLoader getClassLoader() { - String s = System.getProperty("bcel.classloader"); + final String s = System.getProperty("bcel.classloader"); if ((s == null) || "".equals(s)) { throw new IllegalArgumentException("The property 'bcel.classloader' must be defined"); } try { return (java.lang.ClassLoader) Class.forName(s).newInstance(); - } catch (Exception e) { + } catch (final Exception e) { throw new RuntimeException(e.toString(), e); } } @@ -68,7 +68,7 @@ public class JavaWrapper { * @param argv the arguments just as you would pass them directly */ public void runMain( final String class_name, final String[] argv ) throws ClassNotFoundException { - Class<?> cl = loader.loadClass(class_name); + final Class<?> cl = loader.loadClass(class_name); Method method = null; try { method = cl.getMethod("main", new Class[] { @@ -76,13 +76,13 @@ public class JavaWrapper { }); /* Method main is sane ? */ - int m = method.getModifiers(); - Class<?> r = method.getReturnType(); + final int m = method.getModifiers(); + final Class<?> r = method.getReturnType(); if (!(Modifier.isPublic(m) && Modifier.isStatic(m)) || Modifier.isAbstract(m) || (r != Void.TYPE)) { throw new NoSuchMethodException(); } - } catch (NoSuchMethodException no) { + } catch (final NoSuchMethodException no) { System.out.println("In class " + class_name + ": public static void main(String[] argv) is not defined"); return; @@ -91,7 +91,7 @@ public class JavaWrapper { method.invoke(null, new Object[] { argv }); - } catch (Exception ex) { + } catch (final Exception ex) { ex.printStackTrace(); } } @@ -107,10 +107,10 @@ public class JavaWrapper { System.out.println("Missing class name."); return; } - String class_name = argv[0]; - String[] new_argv = new String[argv.length - 1]; + final String class_name = argv[0]; + final String[] new_argv = new String[argv.length - 1]; System.arraycopy(argv, 1, new_argv, 0, new_argv.length); - JavaWrapper wrapper = new JavaWrapper(); + final JavaWrapper wrapper = new JavaWrapper(); wrapper.runMain(class_name, new_argv); } } diff --git a/src/main/java/org/apache/bcel/util/MemorySensitiveClassPathRepository.java b/src/main/java/org/apache/bcel/util/MemorySensitiveClassPathRepository.java index b77f9033..fa3631be 100644 --- a/src/main/java/org/apache/bcel/util/MemorySensitiveClassPathRepository.java +++ b/src/main/java/org/apache/bcel/util/MemorySensitiveClassPathRepository.java @@ -64,7 +64,7 @@ public class MemorySensitiveClassPathRepository implements Repository { */ @Override public JavaClass findClass(final String className) { - SoftReference<JavaClass> ref = loadedClasses.get(className); + final SoftReference<JavaClass> ref = loadedClasses.get(className); if (ref == null) { return null; } @@ -87,13 +87,13 @@ public class MemorySensitiveClassPathRepository implements Repository { throw new IllegalArgumentException("Invalid class name " + className); } className = className.replace('/', '.'); // Just in case, canonical form - JavaClass clazz = findClass(className); + final JavaClass clazz = findClass(className); if (clazz != null) { return clazz; } try { return loadClass(path.getInputStream(className), className); - } catch (IOException e) { + } catch (final IOException e) { throw new ClassNotFoundException("Exception while looking for class " + className + ": " + e, e); } } @@ -112,20 +112,20 @@ public class MemorySensitiveClassPathRepository implements Repository { */ @Override public JavaClass loadClass(final Class<?> clazz) throws ClassNotFoundException { - String className = clazz.getName(); - JavaClass repositoryClass = findClass(className); + final String className = clazz.getName(); + final JavaClass repositoryClass = findClass(className); if (repositoryClass != null) { return repositoryClass; } String name = className; - int i = name.lastIndexOf('.'); + final int i = name.lastIndexOf('.'); if (i > 0) { name = name.substring(i + 1); } JavaClass cls = null; try (InputStream clsStream = clazz.getResourceAsStream(name + ".class")) { return cls = loadClass(clsStream, className); - } catch (IOException e) { + } catch (final IOException e) { return cls; } @@ -134,18 +134,18 @@ public class MemorySensitiveClassPathRepository implements Repository { private JavaClass loadClass(final InputStream is, final String className) throws ClassNotFoundException { try { if (is != null) { - ClassParser parser = new ClassParser(is, className); - JavaClass clazz = parser.parse(); + final ClassParser parser = new ClassParser(is, className); + final JavaClass clazz = parser.parse(); storeClass(clazz); return clazz; } - } catch (IOException e) { + } catch (final IOException e) { throw new ClassNotFoundException("Exception while looking for class " + className + ": " + e, e); } finally { if (is != null) { try { is.close(); - } catch (IOException e) { + } catch (final IOException e) { // ignored } } diff --git a/src/main/java/org/apache/bcel/util/MethodHTML.java b/src/main/java/org/apache/bcel/util/MethodHTML.java index 1c605cb1..6aed1ef7 100644 --- a/src/main/java/org/apache/bcel/util/MethodHTML.java +++ b/src/main/java/org/apache/bcel/util/MethodHTML.java @@ -53,7 +53,7 @@ final class MethodHTML { file.println("<HTML><BODY BGCOLOR=\"#C0C0C0\"><TABLE BORDER=0>"); file.println("<TR><TH ALIGN=LEFT>Access flags</TH><TH ALIGN=LEFT>Type</TH>" + "<TH ALIGN=LEFT>Field name</TH></TR>"); - for (Field field : fields) { + for (final Field field : fields) { writeField(field); } file.println("</TABLE>"); @@ -75,8 +75,8 @@ final class MethodHTML { * @throws java.io.IOException */ private void writeField( final Field field ) throws IOException { - String type = Utility.signatureToString(field.getSignature()); - String name = field.getName(); + final String type = Utility.signatureToString(field.getSignature()); + final String name = field.getName(); String access = Utility.accessToString(field.getAccessFlags()); Attribute[] attributes; access = Utility.replace(access, " ", " "); @@ -90,7 +90,7 @@ final class MethodHTML { } for (int i = 0; i < attributes.length; i++) { if (attributes[i].getTag() == Const.ATTR_CONSTANT_VALUE) { // Default value - String str = ((ConstantValue) attributes[i]).toString(); + final String str = ((ConstantValue) attributes[i]).toString(); // Reference attribute in _attributes.html file.print("<TD>= <A HREF=\"" + class_name + "_attributes.html#" + name + "@" + i + "\" TARGET=\"Attributes\">" + str + "</TD>\n"); @@ -103,18 +103,18 @@ final class MethodHTML { private void writeMethod( final Method method, final int method_number ) { // Get raw signature - String signature = method.getSignature(); + final String signature = method.getSignature(); // Get array of strings containing the argument types - String[] args = Utility.methodSignatureArgumentTypes(signature, false); + final String[] args = Utility.methodSignatureArgumentTypes(signature, false); // Get return type string - String type = Utility.methodSignatureReturnType(signature, false); + final String type = Utility.methodSignatureReturnType(signature, false); // Get method name - String name = method.getName(); + final String name = method.getName(); String html_name; // Get method's access flags String access = Utility.accessToString(method.getAccessFlags()); // Get the method's attributes, the Code Attribute in particular - Attribute[] attributes = method.getAttributes(); + final Attribute[] attributes = method.getAttributes(); /* HTML doesn't like names like <clinit> and spaces are places to break * lines. Both we don't want... */ @@ -136,10 +136,10 @@ final class MethodHTML { for (int i = 0; i < attributes.length; i++) { attribute_html.writeAttribute(attributes[i], "method" + method_number + "@" + i, method_number); - byte tag = attributes[i].getTag(); + final byte tag = attributes[i].getTag(); if (tag == Const.ATTR_EXCEPTIONS) { file.print("<TR VALIGN=TOP><TD COLSPAN=2></TD><TH ALIGN=LEFT>throws</TH><TD>"); - int[] exceptions = ((ExceptionTable) attributes[i]).getExceptionIndexTable(); + final int[] exceptions = ((ExceptionTable) attributes[i]).getExceptionIndexTable(); for (int j = 0; j < exceptions.length; j++) { file.print(constant_html.referenceConstant(exceptions[j])); if (j < exceptions.length - 1) { @@ -148,7 +148,7 @@ final class MethodHTML { } file.println("</TD></TR>"); } else if (tag == Const.ATTR_CODE) { - Attribute[] c_a = ((Code) attributes[i]).getAttributes(); + final Attribute[] c_a = ((Code) attributes[i]).getAttributes(); for (int j = 0; j < c_a.length; j++) { attribute_html.writeAttribute(c_a[j], "method" + method_number + "@" + i + "@" + j, method_number); diff --git a/src/main/java/org/apache/bcel/verifier/GraphicalVerifier.java b/src/main/java/org/apache/bcel/verifier/GraphicalVerifier.java index 63d1fd0b..3d86da0b 100644 --- a/src/main/java/org/apache/bcel/verifier/GraphicalVerifier.java +++ b/src/main/java/org/apache/bcel/verifier/GraphicalVerifier.java @@ -35,7 +35,7 @@ public class GraphicalVerifier { /** Constructor. */ public GraphicalVerifier() { - VerifierAppFrame frame = new VerifierAppFrame(); + final VerifierAppFrame frame = new VerifierAppFrame(); //Frames �berpr�fen, die voreingestellte Gr��e haben //Frames packen, die nutzbare bevorzugte Gr��eninformationen enthalten, z.B. aus ihrem Layout if (packFrame) { @@ -44,8 +44,8 @@ public class GraphicalVerifier { frame.validate(); } //Das Fenster zentrieren - Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension frameSize = frame.getSize(); + final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); + final Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } @@ -65,7 +65,7 @@ public class GraphicalVerifier { public static void main( final String[] args ) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); } new GraphicalVerifier(); diff --git a/src/main/java/org/apache/bcel/verifier/NativeVerifier.java b/src/main/java/org/apache/bcel/verifier/NativeVerifier.java index 98157b4b..1ede20e6 100644 --- a/src/main/java/org/apache/bcel/verifier/NativeVerifier.java +++ b/src/main/java/org/apache/bcel/verifier/NativeVerifier.java @@ -43,7 +43,7 @@ public abstract class NativeVerifier { System.out.println("Verifier front-end: need exactly one argument."); System.exit(1); } - int dotclasspos = args[0].lastIndexOf(".class"); + final int dotclasspos = args[0].lastIndexOf(".class"); if (dotclasspos != -1) { args[0] = args[0].substring(0, dotclasspos); } @@ -51,19 +51,19 @@ public abstract class NativeVerifier { //System.out.println(args[0]); try { Class.forName(args[0]); - } catch (ExceptionInInitializerError eiie) { //subclass of LinkageError! + } catch (final ExceptionInInitializerError eiie) { //subclass of LinkageError! System.out.println("NativeVerifier: ExceptionInInitializerError encountered on '" + args[0] + "'."); System.out.println(eiie); System.exit(1); - } catch (LinkageError le) { + } catch (final LinkageError le) { System.out.println("NativeVerifier: LinkageError encountered on '" + args[0] + "'."); System.out.println(le); System.exit(1); - } catch (ClassNotFoundException cnfe) { + } catch (final ClassNotFoundException cnfe) { System.out.println("NativeVerifier: FILE NOT FOUND: '" + args[0] + "'."); System.exit(1); - } catch (Throwable t) { // OK to catch Throwable here as we call exit. + } catch (final Throwable t) { // OK to catch Throwable here as we call exit. System.out.println("NativeVerifier: Unspecified verification error on '" + args[0] + "'."); System.exit(1); } diff --git a/src/main/java/org/apache/bcel/verifier/TransitiveHull.java b/src/main/java/org/apache/bcel/verifier/TransitiveHull.java index 5807b38b..f4b2dda6 100644 --- a/src/main/java/org/apache/bcel/verifier/TransitiveHull.java +++ b/src/main/java/org/apache/bcel/verifier/TransitiveHull.java @@ -48,7 +48,7 @@ public class TransitiveHull implements VerifierFactoryObserver { } System.out.println(classname); indent += 1; - Verifier v = VerifierFactory.getVerifier(classname); + final Verifier v = VerifierFactory.getVerifier(classname); VerificationResult vr; vr = v.doPass1(); if (vr != VerificationResult.VR_OK) { @@ -60,7 +60,7 @@ public class TransitiveHull implements VerifierFactoryObserver { } if (vr == VerificationResult.VR_OK) { try { - JavaClass jc = Repository.lookupClass(v.getClassName()); + final JavaClass jc = Repository.lookupClass(v.getClassName()); for (int i = 0; i < jc.getMethods().length; i++) { vr = v.doPass3a(i); if (vr != VerificationResult.VR_OK) { @@ -73,7 +73,7 @@ public class TransitiveHull implements VerifierFactoryObserver { + jc.getMethods()[i] + "']:\n" + vr); } } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { System.err.println("Could not find class " + v.getClassName() + " in Repository"); } } @@ -92,12 +92,12 @@ public class TransitiveHull implements VerifierFactoryObserver { System.out.println("Need exactly one argument: The root class to verify."); System.exit(1); } - int dotclasspos = args[0].lastIndexOf(".class"); + final int dotclasspos = args[0].lastIndexOf(".class"); if (dotclasspos != -1) { args[0] = args[0].substring(0, dotclasspos); } args[0] = args[0].replace('/', '.'); - TransitiveHull th = new TransitiveHull(); + final TransitiveHull th = new TransitiveHull(); VerifierFactory.attach(th); VerifierFactory.getVerifier(args[0]); // the observer is called back and does the actual trick. VerifierFactory.detach(th); diff --git a/src/main/java/org/apache/bcel/verifier/VerificationResult.java b/src/main/java/org/apache/bcel/verifier/VerificationResult.java index faa3fd7f..53a69753 100644 --- a/src/main/java/org/apache/bcel/verifier/VerificationResult.java +++ b/src/main/java/org/apache/bcel/verifier/VerificationResult.java @@ -101,7 +101,7 @@ public class VerificationResult { if (!(o instanceof VerificationResult)) { return false; } - VerificationResult other = (VerificationResult) o; + final VerificationResult other = (VerificationResult) o; return (other.numeric == this.numeric) && other.detailMessage.equals(this.detailMessage); } diff --git a/src/main/java/org/apache/bcel/verifier/Verifier.java b/src/main/java/org/apache/bcel/verifier/Verifier.java index c762bf69..2534df6c 100644 --- a/src/main/java/org/apache/bcel/verifier/Verifier.java +++ b/src/main/java/org/apache/bcel/verifier/Verifier.java @@ -79,7 +79,7 @@ public class Verifier { /** Returns the VerificationResult for the given pass. */ public VerificationResult doPass3a( final int method_no ) { - String key = Integer.toString(method_no); + final String key = Integer.toString(method_no); Pass3aVerifier p3av; p3av = p3avs.get(key); if (p3avs.get(key) == null) { @@ -92,7 +92,7 @@ public class Verifier { /** Returns the VerificationResult for the given pass. */ public VerificationResult doPass3b( final int method_no ) { - String key = Integer.toString(method_no); + final String key = Integer.toString(method_no); Pass3bVerifier p3bv; p3bv = p3bvs.get(key); if (p3bvs.get(key) == null) { @@ -145,32 +145,32 @@ public class Verifier { * A prefix shows from which verifying pass a message originates. */ public String[] getMessages() throws ClassNotFoundException { - List<String> messages = new ArrayList<>(); + final List<String> messages = new ArrayList<>(); if (p1v != null) { - String[] p1m = p1v.getMessages(); - for (String element : p1m) { + final String[] p1m = p1v.getMessages(); + for (final String element : p1m) { messages.add("Pass 1: " + element); } } if (p2v != null) { - String[] p2m = p2v.getMessages(); - for (String element : p2m) { + final String[] p2m = p2v.getMessages(); + for (final String element : p2m) { messages.add("Pass 2: " + element); } } - for (Pass3aVerifier pv : p3avs.values()) { - String[] p3am = pv.getMessages(); - int meth = pv.getMethodNo(); - for (String element : p3am) { + for (final Pass3aVerifier pv : p3avs.values()) { + final String[] p3am = pv.getMessages(); + final int meth = pv.getMethodNo(); + for (final String element : p3am) { messages.add("Pass 3a, method " + meth + " ('" + org.apache.bcel.Repository.lookupClass(classname).getMethods()[meth] + "'): " + element); } } - for (Pass3bVerifier pv : p3bvs.values()) { - String[] p3bm = pv.getMessages(); - int meth = pv.getMethodNo(); - for (String element : p3bm) { + for (final Pass3bVerifier pv : p3bvs.values()) { + final String[] p3bm = pv.getMessages(); + final int meth = pv.getMethodNo(); + for (final String element : p3bm) { messages.add("Pass 3b, method " + meth + " ('" + org.apache.bcel.Repository.lookupClass(classname).getMethods()[meth] + "'): " + element); @@ -197,21 +197,21 @@ public class Verifier { for (int k = 0; k < args.length; k++) { try { if (args[k].endsWith(".class")) { - int dotclasspos = args[k].lastIndexOf(".class"); + final int dotclasspos = args[k].lastIndexOf(".class"); if (dotclasspos != -1) { args[k] = args[k].substring(0, dotclasspos); } } args[k] = args[k].replace('/', '.'); System.out.println("Now verifying: " + args[k] + "\n"); - Verifier v = VerifierFactory.getVerifier(args[k]); + final Verifier v = VerifierFactory.getVerifier(args[k]); VerificationResult vr; vr = v.doPass1(); System.out.println("Pass 1:\n" + vr); vr = v.doPass2(); System.out.println("Pass 2:\n" + vr); if (vr == VerificationResult.VR_OK) { - JavaClass jc = org.apache.bcel.Repository.lookupClass(args[k]); + final JavaClass jc = org.apache.bcel.Repository.lookupClass(args[k]); for (int i = 0; i < jc.getMethods().length; i++) { vr = v.doPass3a(i); System.out.println("Pass 3a, method number " + i + " ['" @@ -222,11 +222,11 @@ public class Verifier { } } System.out.println("Warnings:"); - String[] warnings = v.getMessages(); + final String[] warnings = v.getMessages(); if (warnings.length == 0) { System.out.println("<none>"); } - for (String warning : warnings) { + for (final String warning : warnings) { System.out.println(warning); } System.out.println("\n"); @@ -234,7 +234,7 @@ public class Verifier { v.flush(); org.apache.bcel.Repository.clearCache(); System.gc(); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { e.printStackTrace(); } } diff --git a/src/main/java/org/apache/bcel/verifier/VerifierAppFrame.java b/src/main/java/org/apache/bcel/verifier/VerifierAppFrame.java index 50dfa712..e097e285 100644 --- a/src/main/java/org/apache/bcel/verifier/VerifierAppFrame.java +++ b/src/main/java/org/apache/bcel/verifier/VerifierAppFrame.java @@ -98,7 +98,7 @@ public class VerifierAppFrame extends JFrame { enableEvents(AWTEvent.WINDOW_EVENT_MASK); try { jbInit(); - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); } } @@ -244,7 +244,7 @@ public class VerifierAppFrame extends JFrame { current_class = classNamesJList.getSelectedValue(); try { verify(); - } catch (ClassNotFoundException ex) { + } catch (final ClassNotFoundException ex) { // FIXME: report the error using the GUI ex.printStackTrace(); } @@ -254,7 +254,7 @@ public class VerifierAppFrame extends JFrame { private void verify() throws ClassNotFoundException { setTitle("PLEASE WAIT"); - Verifier v = VerifierFactory.getVerifier(current_class); + final Verifier v = VerifierFactory.getVerifier(current_class); v.flush(); // Don't cache the verification result for this class. VerificationResult vr; vr = v.doPass1(); @@ -285,14 +285,14 @@ public class VerifierAppFrame extends JFrame { } else { // must be Verified_OK, because Pass1 was OK (cannot be Verified_NOTYET). pass2TextPane.setText(vr.getMessage()); pass2TextPane.setBackground(Color.green); - JavaClass jc = Repository.lookupClass(current_class); + final JavaClass jc = Repository.lookupClass(current_class); /* boolean all3aok = true; boolean all3bok = true; String all3amsg = ""; String all3bmsg = ""; */ - String[] methodnames = new String[jc.getMethods().length]; + final String[] methodnames = new String[jc.getMethods().length]; for (int i = 0; i < jc.getMethods().length; i++) { methodnames[i] = jc.getMethods()[i].toString().replace('\n', ' ').replace('\t', ' '); @@ -303,9 +303,9 @@ public class VerifierAppFrame extends JFrame { pass3bJList.setSelectionInterval(0, jc.getMethods().length - 1); } } - String[] msgs = v.getMessages(); + final String[] msgs = v.getMessages(); messagesTextPane.setBackground(msgs.length == 0 ? Color.green : Color.yellow); - StringBuilder allmsgs = new StringBuilder(); + final StringBuilder allmsgs = new StringBuilder(); for (int i = 0; i < msgs.length; i++) { msgs[i] = msgs[i].replace('\n', ' '); allmsgs.append(msgs[i]).append("\n\n"); @@ -316,7 +316,7 @@ public class VerifierAppFrame extends JFrame { void newFileMenuItem_actionPerformed( final ActionEvent e ) { - String classname = JOptionPane + final String classname = JOptionPane .showInputDialog("Please enter the fully qualified name of a class or interface to verify:"); if ((classname == null) || (classname.isEmpty())) { return; @@ -330,13 +330,13 @@ public class VerifierAppFrame extends JFrame { if (e.getValueIsAdjusting()) { return; } - Verifier v = VerifierFactory.getVerifier(current_class); - StringBuilder all3amsg = new StringBuilder(); + final Verifier v = VerifierFactory.getVerifier(current_class); + final StringBuilder all3amsg = new StringBuilder(); boolean all3aok = true; boolean rejected = false; for (int i = 0; i < pass3aJList.getModel().getSize(); i++) { if (pass3aJList.isSelectedIndex(i)) { - VerificationResult vr = v.doPass3a(i); + final VerificationResult vr = v.doPass3a(i); if (vr.getStatus() == VerificationResult.VERIFIED_REJECTED) { all3aok = false; rejected = true; @@ -346,7 +346,7 @@ public class VerifierAppFrame extends JFrame { jc = Repository.lookupClass(v.getClassName()); all3amsg.append("Method '").append(jc.getMethods()[i]).append("': ") .append(vr.getMessage().replace('\n', ' ') ).append("\n\n"); - } catch (ClassNotFoundException ex) { + } catch (final ClassNotFoundException ex) { // FIXME: handle the error ex.printStackTrace(); } @@ -361,13 +361,13 @@ public class VerifierAppFrame extends JFrame { if (e.getValueIsAdjusting()) { return; } - Verifier v = VerifierFactory.getVerifier(current_class); - StringBuilder all3bmsg = new StringBuilder(); + final Verifier v = VerifierFactory.getVerifier(current_class); + final StringBuilder all3bmsg = new StringBuilder(); boolean all3bok = true; boolean rejected = false; for (int i = 0; i < pass3bJList.getModel().getSize(); i++) { if (pass3bJList.isSelectedIndex(i)) { - VerificationResult vr = v.doPass3b(i); + final VerificationResult vr = v.doPass3b(i); if (vr.getStatus() == VerificationResult.VERIFIED_REJECTED) { all3bok = false; rejected = true; @@ -377,7 +377,7 @@ public class VerifierAppFrame extends JFrame { jc = Repository.lookupClass(v.getClassName()); all3bmsg.append("Method '").append(jc.getMethods()[i]).append("': ") .append(vr.getMessage().replace('\n', ' ')).append("\n\n"); - } catch (ClassNotFoundException ex) { + } catch (final ClassNotFoundException ex) { // FIXME: handle the error ex.printStackTrace(); } diff --git a/src/main/java/org/apache/bcel/verifier/VerifierFactory.java b/src/main/java/org/apache/bcel/verifier/VerifierFactory.java index b828addb..d768f7ff 100644 --- a/src/main/java/org/apache/bcel/verifier/VerifierFactory.java +++ b/src/main/java/org/apache/bcel/verifier/VerifierFactory.java @@ -71,7 +71,7 @@ public class VerifierFactory { */ private static void notify( final String fully_qualified_classname ) { // notify the observers - for (VerifierFactoryObserver vfo : observers) { + for (final VerifierFactoryObserver vfo : observers) { vfo.update(fully_qualified_classname); } } @@ -85,7 +85,7 @@ public class VerifierFactory { * referenced class files. */ public static Verifier[] getVerifiers() { - Verifier[] vs = new Verifier[hashMap.values().size()]; + final Verifier[] vs = new Verifier[hashMap.values().size()]; return hashMap.values().toArray(vs); // Because vs is big enough, vs is used to store the values into and returned! } diff --git a/src/main/java/org/apache/bcel/verifier/VerifierFactoryListModel.java b/src/main/java/org/apache/bcel/verifier/VerifierFactoryListModel.java index bcf40392..90743edf 100644 --- a/src/main/java/org/apache/bcel/verifier/VerifierFactoryListModel.java +++ b/src/main/java/org/apache/bcel/verifier/VerifierFactoryListModel.java @@ -46,14 +46,14 @@ public class VerifierFactoryListModel implements VerifierFactoryObserver, @Override public synchronized void update( final String s ) { - Verifier[] verifiers = VerifierFactory.getVerifiers(); - int num_of_verifiers = verifiers.length; + final Verifier[] verifiers = VerifierFactory.getVerifiers(); + final int num_of_verifiers = verifiers.length; cache.clear(); - for (Verifier verifier : verifiers) { + for (final Verifier verifier : verifiers) { cache.add(verifier.getClassName()); } - for (ListDataListener listener : listeners) { - ListDataEvent e = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, num_of_verifiers - 1); + for (final ListDataListener listener : listeners) { + final ListDataEvent e = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, num_of_verifiers - 1); listener.contentsChanged(e); } } diff --git a/src/main/java/org/apache/bcel/verifier/VerifyDialog.java b/src/main/java/org/apache/bcel/verifier/VerifyDialog.java index 12b0a9ef..e6dcfc3b 100644 --- a/src/main/java/org/apache/bcel/verifier/VerifyDialog.java +++ b/src/main/java/org/apache/bcel/verifier/VerifyDialog.java @@ -153,7 +153,7 @@ public class VerifyDialog extends javax.swing.JDialog { */ public VerifyDialog(String fully_qualified_class_name) { super(); - int dotclasspos = fully_qualified_class_name.lastIndexOf(".class"); + final int dotclasspos = fully_qualified_class_name.lastIndexOf(".class"); if (dotclasspos != -1) { fully_qualified_class_name = fully_qualified_class_name.substring(0, dotclasspos); } @@ -171,7 +171,7 @@ public class VerifyDialog extends javax.swing.JDialog { this.pass1Button_ActionPerformed(arg1); // user code begin {2} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {3} // user code end handleException(ivjExc); @@ -187,7 +187,7 @@ public class VerifyDialog extends javax.swing.JDialog { this.pass2Button_ActionPerformed(arg1); // user code begin {2} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {3} // user code end handleException(ivjExc); @@ -203,7 +203,7 @@ public class VerifyDialog extends javax.swing.JDialog { this.pass4Button_ActionPerformed(arg1); // user code begin {2} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {3} // user code end handleException(ivjExc); @@ -219,7 +219,7 @@ public class VerifyDialog extends javax.swing.JDialog { this.flushButton_ActionPerformed(arg1); // user code begin {2} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {3} // user code end handleException(ivjExc); @@ -253,7 +253,7 @@ public class VerifyDialog extends javax.swing.JDialog { ivjFlushButton.setActionCommand("FlushButton"); // user code begin {1} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); @@ -279,7 +279,7 @@ public class VerifyDialog extends javax.swing.JDialog { getJDialogContentPane().add(getFlushButton(), getFlushButton().getName()); // user code begin {1} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); @@ -301,7 +301,7 @@ public class VerifyDialog extends javax.swing.JDialog { ivjPass1Button.setActionCommand("Button1"); // user code begin {1} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); @@ -322,7 +322,7 @@ public class VerifyDialog extends javax.swing.JDialog { ivjPass1Panel.setBounds(30, 30, 50, 50); // user code begin {1} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); @@ -344,7 +344,7 @@ public class VerifyDialog extends javax.swing.JDialog { ivjPass2Button.setActionCommand("Button2"); // user code begin {1} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); @@ -365,7 +365,7 @@ public class VerifyDialog extends javax.swing.JDialog { ivjPass2Panel.setBounds(30, 90, 50, 50); // user code begin {1} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); @@ -387,7 +387,7 @@ public class VerifyDialog extends javax.swing.JDialog { ivjPass3Button.setActionCommand("Button2"); // user code begin {1} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); @@ -408,7 +408,7 @@ public class VerifyDialog extends javax.swing.JDialog { ivjPass3Panel.setBounds(30, 150, 50, 50); // user code begin {1} // user code end - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { // user code begin {2} // user code end handleException(ivjExc); @@ -457,7 +457,7 @@ public class VerifyDialog extends javax.swing.JDialog { setResizable(false); setContentPane(getJDialogContentPane()); initConnections(); - } catch (java.lang.Throwable ivjExc) { + } catch (final java.lang.Throwable ivjExc) { handleException(ivjExc); } // user code begin {2} @@ -474,7 +474,7 @@ public class VerifyDialog extends javax.swing.JDialog { */ public static void main( final java.lang.String[] args ) { classes_to_verify = args.length; - for (String arg : args) { + for (final String arg : args) { try { VerifyDialog aVerifyDialog; aVerifyDialog = new VerifyDialog(arg); @@ -490,7 +490,7 @@ public class VerifyDialog extends javax.swing.JDialog { } }); aVerifyDialog.setVisible(true); - } catch (Throwable exception) { + } catch (final Throwable exception) { System.err.println("Exception occurred in main() of javax.swing.JDialog"); exception.printStackTrace(System.out); } @@ -500,8 +500,8 @@ public class VerifyDialog extends javax.swing.JDialog { /** Machine-generated. */ public void pass1Button_ActionPerformed( final java.awt.event.ActionEvent actionEvent ) { - Verifier v = VerifierFactory.getVerifier(class_name); - VerificationResult vr = v.doPass1(); + final Verifier v = VerifierFactory.getVerifier(class_name); + final VerificationResult vr = v.doPass1(); if (vr.getStatus() == VerificationResult.VERIFIED_OK) { getPass1Panel().setBackground(Color.green); getPass1Panel().repaint(); @@ -516,8 +516,8 @@ public class VerifyDialog extends javax.swing.JDialog { /** Machine-generated. */ public void pass2Button_ActionPerformed( final java.awt.event.ActionEvent actionEvent ) { pass1Button_ActionPerformed(actionEvent); - Verifier v = VerifierFactory.getVerifier(class_name); - VerificationResult vr = v.doPass2(); + final Verifier v = VerifierFactory.getVerifier(class_name); + final VerificationResult vr = v.doPass2(); if (vr.getStatus() == VerificationResult.VERIFIED_OK) { getPass2Panel().setBackground(Color.green); getPass2Panel().repaint(); @@ -537,13 +537,13 @@ public class VerifyDialog extends javax.swing.JDialog { public void pass4Button_ActionPerformed( final java.awt.event.ActionEvent actionEvent ) { pass2Button_ActionPerformed(actionEvent); Color color = Color.green; - Verifier v = VerifierFactory.getVerifier(class_name); + final Verifier v = VerifierFactory.getVerifier(class_name); VerificationResult vr = v.doPass2(); if (vr.getStatus() == VerificationResult.VERIFIED_OK) { JavaClass jc = null; try { jc = Repository.lookupClass(class_name); - int nr = jc.getMethods().length; + final int nr = jc.getMethods().length; for (int i = 0; i < nr; i++) { vr = v.doPass3b(i); if (vr.getStatus() != VerificationResult.VERIFIED_OK) { @@ -551,7 +551,7 @@ public class VerifyDialog extends javax.swing.JDialog { break; } } - } catch (ClassNotFoundException ex) { + } catch (final ClassNotFoundException ex) { // FIXME: report the error ex.printStackTrace(); } diff --git a/src/main/java/org/apache/bcel/verifier/exc/AssertionViolatedException.java b/src/main/java/org/apache/bcel/verifier/exc/AssertionViolatedException.java index 7f20b42b..005ad047 100644 --- a/src/main/java/org/apache/bcel/verifier/exc/AssertionViolatedException.java +++ b/src/main/java/org/apache/bcel/verifier/exc/AssertionViolatedException.java @@ -78,7 +78,7 @@ public final class AssertionViolatedException extends RuntimeException{ * DO NOT USE. It's for experimental testing during development only. */ public static void main(final String[] args) { - AssertionViolatedException ave = new AssertionViolatedException("Oops!"); + final AssertionViolatedException ave = new AssertionViolatedException("Oops!"); ave.extendMessage("\nFOUND:\n\t","\nExiting!!\n"); throw ave; } diff --git a/src/main/java/org/apache/bcel/verifier/exc/Utility.java b/src/main/java/org/apache/bcel/verifier/exc/Utility.java index 2d9f031d..97c09a20 100644 --- a/src/main/java/org/apache/bcel/verifier/exc/Utility.java +++ b/src/main/java/org/apache/bcel/verifier/exc/Utility.java @@ -32,8 +32,8 @@ public final class Utility{ /** This method returns the stack trace of a Throwable instance as a String. */ public static String getStackTrace(final Throwable t) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); return sw.toString(); } diff --git a/src/main/java/org/apache/bcel/verifier/statics/IntList.java b/src/main/java/org/apache/bcel/verifier/statics/IntList.java index 1e736235..833e515e 100644 --- a/src/main/java/org/apache/bcel/verifier/statics/IntList.java +++ b/src/main/java/org/apache/bcel/verifier/statics/IntList.java @@ -39,9 +39,9 @@ public class IntList{ } /** Checks if the specified int is already in the list. */ boolean contains(final int i) { - Integer[] ints = new Integer[theList.size()]; + final Integer[] ints = new Integer[theList.size()]; theList.toArray(ints); - for (Integer k : ints) { + for (final Integer k : ints) { if (i == k.intValue()) { return true; } diff --git a/src/main/java/org/apache/bcel/verifier/statics/Pass1Verifier.java b/src/main/java/org/apache/bcel/verifier/statics/Pass1Verifier.java index 78f94958..9d1e070c 100644 --- a/src/main/java/org/apache/bcel/verifier/statics/Pass1Verifier.java +++ b/src/main/java/org/apache/bcel/verifier/statics/Pass1Verifier.java @@ -56,7 +56,7 @@ public final class Pass1Verifier extends PassVerifier{ if (jc == null) { try { jc = Repository.lookupClass(myOwner.getClassName()); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: currently, Pass1Verifier treats jc == null as a special // case, so we don't need to do anything here. A better solution // would be to simply throw the ClassNotFoundException @@ -160,13 +160,13 @@ public final class Pass1Verifier extends PassVerifier{ } } - catch(LoadingException e) { + catch(final LoadingException e) { return new VerificationResult(VerificationResult.VERIFIED_REJECTED, e.getMessage()); } - catch(ClassFormatException e) { + catch(final ClassFormatException e) { return new VerificationResult(VerificationResult.VERIFIED_REJECTED, e.getMessage()); } - catch(RuntimeException e) { + catch(final RuntimeException e) { // BCEL does not catch every possible RuntimeException; e.g. if // a constant pool index is referenced that does not exist. return new VerificationResult(VerificationResult.VERIFIED_REJECTED, "Parsing via BCEL did not succeed. "+ diff --git a/src/main/java/org/apache/bcel/verifier/statics/Pass2Verifier.java b/src/main/java/org/apache/bcel/verifier/statics/Pass2Verifier.java index 550b60e8..219ae56b 100644 --- a/src/main/java/org/apache/bcel/verifier/statics/Pass2Verifier.java +++ b/src/main/java/org/apache/bcel/verifier/statics/Pass2Verifier.java @@ -149,7 +149,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { @Override public VerificationResult do_verify() { try { - VerificationResult vr1 = myOwner.doPass1(); + final VerificationResult vr1 = myOwner.doPass1(); if (vr1.equals(VerificationResult.VR_OK)) { // For every method, we could have information about the local variables out of LocalVariableTable attributes of @@ -163,14 +163,14 @@ public final class Pass2Verifier extends PassVerifier implements Constants { every_class_has_an_accessible_superclass(); final_methods_are_not_overridden(); } - catch (ClassConstraintException cce) { + catch (final ClassConstraintException cce) { vr = new VerificationResult(VerificationResult.VERIFIED_REJECTED, cce.getMessage()); } return vr; } return VerificationResult.VR_NOTYET; - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: this might not be the best way to handle missing classes. throw new AssertionViolatedException("Missing class: " + e, e); } @@ -191,7 +191,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { */ private void every_class_has_an_accessible_superclass() { try { - Set<String> hs = new HashSet<>(); // save class names to detect circular inheritance + final Set<String> hs = new HashSet<>(); // save class names to detect circular inheritance JavaClass jc = Repository.lookupClass(myOwner.getClassName()); int supidx = -1; @@ -205,12 +205,12 @@ public final class Pass2Verifier extends PassVerifier implements Constants { } } else{ - String supername = jc.getSuperclassName(); + final String supername = jc.getSuperclassName(); if (! hs.add(supername)) { // If supername already is in the list throw new ClassConstraintException("Circular superclass hierarchy detected."); } - Verifier v = VerifierFactory.getVerifier(supername); - VerificationResult vr = v.doPass1(); + final Verifier v = VerifierFactory.getVerifier(supername); + final VerificationResult vr = v.doPass1(); if (vr != VerificationResult.VR_OK) { throw new ClassConstraintException("Could not load in ancestor class '"+supername+"'."); @@ -224,7 +224,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { } } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: this might not be the best way to handle missing classes. throw new AssertionViolatedException("Missing class: " + e, e); } @@ -243,16 +243,16 @@ public final class Pass2Verifier extends PassVerifier implements Constants { */ private void final_methods_are_not_overridden() { try { - Map<String, String> hashmap = new HashMap<>(); + final Map<String, String> hashmap = new HashMap<>(); JavaClass jc = Repository.lookupClass(myOwner.getClassName()); int supidx = -1; while (supidx != 0) { supidx = jc.getSuperclassNameIndex(); - Method[] methods = jc.getMethods(); - for (Method method : methods) { - String nameAndSig = method.getName() + method.getSignature(); + final Method[] methods = jc.getMethods(); + for (final Method method : methods) { + final String nameAndSig = method.getName() + method.getSignature(); if (hashmap.containsKey(nameAndSig)) { if (method.isFinal()) { @@ -280,7 +280,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { // Well, for OBJECT this returns OBJECT so it works (could return anything but must not throw an Exception). } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: this might not be the best way to handle missing classes. throw new AssertionViolatedException("Missing class: " + e, e); } @@ -298,10 +298,10 @@ public final class Pass2Verifier extends PassVerifier implements Constants { // Most of the consistency is handled internally by BCEL; here // we only have to verify if the indices of the constants point // to constants of the appropriate type and such. - JavaClass jc = Repository.lookupClass(myOwner.getClassName()); + final JavaClass jc = Repository.lookupClass(myOwner.getClassName()); new CPESSC_Visitor(jc); // constructor implicitly traverses jc - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: this might not be the best way to handle missing classes. throw new AssertionViolatedException("Missing class: " + e, e); } @@ -365,7 +365,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { if ((index < 0) || (index >= cplen)) { throw new ClassConstraintException("Invalid index '"+index+"' used by '"+tostring(referrer)+"'."); } - Constant c = cp.getConstant(index); + final Constant c = cp.getConstant(index); if (! shouldbe.isInstance(c)) { /* String isnot = shouldbe.toString().substring(shouldbe.toString().lastIndexOf(".")+1); //Cut all before last "." */ throw new ClassCastException("Illegal constant '"+tostring(c)+"' at index '"+ @@ -377,15 +377,15 @@ public final class Pass2Verifier extends PassVerifier implements Constants { /////////////////////////////////////// @Override public void visitJavaClass(final JavaClass obj) { - Attribute[] atts = obj.getAttributes(); + final Attribute[] atts = obj.getAttributes(); boolean foundSourceFile = false; boolean foundInnerClasses = false; // Is there an InnerClass referenced? // This is a costly check; existing verifiers don't do it! - boolean hasInnerClass = new InnerClassDetector(jc).innerClassReferenced(); + final boolean hasInnerClass = new InnerClassDetector(jc).innerClassReferenced(); - for (Attribute att : atts) { + for (final Attribute att : atts) { if ((!(att instanceof SourceFile)) && (!(att instanceof Deprecated)) && (!(att instanceof InnerClasses)) && @@ -570,7 +570,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { checkIndex(obj, obj.getNameIndex(), CONST_Utf8); - String name = obj.getName(); + final String name = obj.getName(); if (! validFieldName(name)) { throw new ClassConstraintException("Field '"+tostring(obj)+"' has illegal name '"+obj.getName()+"'."); } @@ -578,16 +578,16 @@ public final class Pass2Verifier extends PassVerifier implements Constants { // A descriptor is often named signature in BCEL checkIndex(obj, obj.getSignatureIndex(), CONST_Utf8); - String sig = ((ConstantUtf8) (cp.getConstant(obj.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor) + final String sig = ((ConstantUtf8) (cp.getConstant(obj.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor) try{ Type.getType(sig); /* Don't need the return value */ } - catch (ClassFormatException cfe) { + catch (final ClassFormatException cfe) { throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe); } - String nameanddesc = name+sig; + final String nameanddesc = name+sig; if (field_names_and_desc.contains(nameanddesc)) { throw new ClassConstraintException("No two fields (like '"+tostring(obj)+ "') are allowed have same names and descriptors!"); @@ -599,8 +599,8 @@ public final class Pass2Verifier extends PassVerifier implements Constants { field_names_and_desc.add(nameanddesc); field_names.add(name); - Attribute[] atts = obj.getAttributes(); - for (Attribute att : atts) { + final Attribute[] atts = obj.getAttributes(); + for (final Attribute att : atts) { if ((!(att instanceof ConstantValue)) && (!(att instanceof Synthetic)) && (!(att instanceof Deprecated))) { @@ -621,7 +621,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { checkIndex(obj, obj.getNameIndex(), CONST_Utf8); - String name = obj.getName(); + final String name = obj.getName(); if (! validMethodName(name, true)) { throw new ClassConstraintException("Method '"+tostring(obj)+"' has illegal name '"+name+"'."); } @@ -629,7 +629,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { // A descriptor is often named signature in BCEL checkIndex(obj, obj.getSignatureIndex(), CONST_Utf8); - String sig = ((ConstantUtf8) (cp.getConstant(obj.getSignatureIndex()))).getBytes(); // Method's signature(=descriptor) + final String sig = ((ConstantUtf8) (cp.getConstant(obj.getSignatureIndex()))).getBytes(); // Method's signature(=descriptor) Type t; Type[] ts; // needed below the try block. @@ -637,7 +637,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { t = Type.getReturnType(sig); ts = Type.getArgumentTypes(sig); } - catch (ClassFormatException cfe) { + catch (final ClassFormatException cfe) { throw new ClassConstraintException( "Illegal descriptor (==signature) '"+sig+"' used by Method '"+tostring(obj)+"'.", cfe); } @@ -648,22 +648,22 @@ public final class Pass2Verifier extends PassVerifier implements Constants { act = ((ArrayType) act).getBasicType(); } if (act instanceof ObjectType) { - Verifier v = VerifierFactory.getVerifier( ((ObjectType) act).getClassName() ); - VerificationResult vr = v.doPass1(); + final Verifier v = VerifierFactory.getVerifier( ((ObjectType) act).getClassName() ); + final VerificationResult vr = v.doPass1(); if (vr != VerificationResult.VR_OK) { throw new ClassConstraintException( "Method '"+tostring(obj)+"' has a return type that does not pass verification pass 1: '"+vr+"'."); } } - for (Type element : ts) { + for (final Type element : ts) { act = element; if (act instanceof ArrayType) { act = ((ArrayType) act).getBasicType(); } if (act instanceof ObjectType) { - Verifier v = VerifierFactory.getVerifier( ((ObjectType) act).getClassName() ); - VerificationResult vr = v.doPass1(); + final Verifier v = VerifierFactory.getVerifier( ((ObjectType) act).getClassName() ); + final VerificationResult vr = v.doPass1(); if (vr != VerificationResult.VR_OK) { throw new ClassConstraintException( "Method '"+tostring(obj)+"' has an argument type that does not pass verification pass 1: '"+vr+"'."); @@ -783,16 +783,16 @@ public final class Pass2Verifier extends PassVerifier implements Constants { " ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_STRICT set (ignored)."); } - String nameanddesc = name+sig; + final String nameanddesc = name+sig; if (method_names_and_desc.contains(nameanddesc)) { throw new ClassConstraintException( "No two methods (like '"+tostring(obj)+"') are allowed have same names and desciptors!"); } method_names_and_desc.add(nameanddesc); - Attribute[] atts = obj.getAttributes(); + final Attribute[] atts = obj.getAttributes(); int num_code_atts = 0; - for (Attribute att : atts) { + for (final Attribute att : atts) { if ((!(att instanceof Code)) && (!(att instanceof ExceptionTable)) && (!(att instanceof Synthetic)) && @@ -828,7 +828,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { checkIndex(obj, obj.getNameIndex(), CONST_Utf8); - String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); + final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); if (! name.equals("SourceFile")) { throw new ClassConstraintException( "The SourceFile attribute '"+tostring(obj)+"' is not correctly named 'SourceFile' but '"+name+"'."); @@ -836,8 +836,8 @@ public final class Pass2Verifier extends PassVerifier implements Constants { checkIndex(obj, obj.getSourceFileIndex(), CONST_Utf8); - String sourcefilename = ((ConstantUtf8) cp.getConstant(obj.getSourceFileIndex())).getBytes(); //==obj.getSourceFileName() ? - String sourcefilenamelc = sourcefilename.toLowerCase(Locale.ENGLISH); + final String sourcefilename = ((ConstantUtf8) cp.getConstant(obj.getSourceFileIndex())).getBytes(); //==obj.getSourceFileName() ? + final String sourcefilenamelc = sourcefilename.toLowerCase(Locale.ENGLISH); if ( (sourcefilename.indexOf('/') != -1) || (sourcefilename.indexOf('\\') != -1) || @@ -852,7 +852,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { public void visitDeprecated(final Deprecated obj) {//vmspec2 4.7.10 checkIndex(obj, obj.getNameIndex(), CONST_Utf8); - String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); + final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); if (! name.equals("Deprecated")) { throw new ClassConstraintException("The Deprecated attribute '"+tostring(obj)+ "' is not correctly named 'Deprecated' but '"+name+"'."); @@ -861,7 +861,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { @Override public void visitSynthetic(final Synthetic obj) {//vmspec2 4.7.6 checkIndex(obj, obj.getNameIndex(), CONST_Utf8); - String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); + final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); if (! name.equals("Synthetic")) { throw new ClassConstraintException( "The Synthetic attribute '"+tostring(obj)+"' is not correctly named 'Synthetic' but '"+name+"'."); @@ -874,21 +874,21 @@ public final class Pass2Verifier extends PassVerifier implements Constants { checkIndex(obj, obj.getNameIndex(), CONST_Utf8); - String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); + final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); if (! name.equals("InnerClasses")) { throw new ClassConstraintException( "The InnerClasses attribute '"+tostring(obj)+"' is not correctly named 'InnerClasses' but '"+name+"'."); } - InnerClass[] ics = obj.getInnerClasses(); + final InnerClass[] ics = obj.getInnerClasses(); - for (InnerClass ic : ics) { + for (final InnerClass ic : ics) { checkIndex(obj, ic.getInnerClassIndex(), CONST_Class); - int outer_idx = ic.getOuterClassIndex(); + final int outer_idx = ic.getOuterClassIndex(); if (outer_idx != 0) { checkIndex(obj, outer_idx, CONST_Class); } - int innername_idx = ic.getInnerNameIndex(); + final int innername_idx = ic.getInnerNameIndex(); if (innername_idx != 0) { checkIndex(obj, innername_idx, CONST_Utf8); } @@ -912,23 +912,23 @@ public final class Pass2Verifier extends PassVerifier implements Constants { // not a constant! checkIndex(obj, obj.getNameIndex(), CONST_Utf8); - String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); + final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); if (! name.equals("ConstantValue")) { throw new ClassConstraintException( "The ConstantValue attribute '"+tostring(obj)+"' is not correctly named 'ConstantValue' but '"+name+"'."); } - Object pred = carrier.predecessor(); + final Object pred = carrier.predecessor(); if (pred instanceof Field) { //ConstantValue attributes are quite senseless if the predecessor is not a field. - Field f = (Field) pred; + final Field f = (Field) pred; // Field constraints have been checked before -- so we are safe using their type information. - Type field_type = Type.getType(((ConstantUtf8) (cp.getConstant(f.getSignatureIndex()))).getBytes()); + final Type field_type = Type.getType(((ConstantUtf8) (cp.getConstant(f.getSignatureIndex()))).getBytes()); - int index = obj.getConstantValueIndex(); + final int index = obj.getConstantValueIndex(); if ((index < 0) || (index >= cplen)) { throw new ClassConstraintException("Invalid index '"+index+"' used by '"+tostring(obj)+"'."); } - Constant c = cp.getConstant(index); + final Constant c = cp.getConstant(index); if (CONST_Long.isInstance(c) && field_type.equals(Type.LONG)) { return; @@ -964,7 +964,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { checkIndex(obj, obj.getNameIndex(), CONST_Utf8); - String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); + final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); if (! name.equals("Code")) { throw new ClassConstraintException( "The Code attribute '"+tostring(obj)+"' is not correctly named 'Code' but '"+name+"'."); @@ -985,15 +985,15 @@ public final class Pass2Verifier extends PassVerifier implements Constants { } //In JustIce, the check for correct offsets into the code array is delayed to Pass 3a. - CodeException[] exc_table = obj.getExceptionTable(); - for (CodeException element : exc_table) { - int exc_index = element.getCatchType(); + final CodeException[] exc_table = obj.getExceptionTable(); + for (final CodeException element : exc_table) { + final int exc_index = element.getCatchType(); if (exc_index != 0) { // if 0, it catches all Throwables checkIndex(obj, exc_index, CONST_Class); - ConstantClass cc = (ConstantClass) (cp.getConstant(exc_index)); + final ConstantClass cc = (ConstantClass) (cp.getConstant(exc_index)); // cannot be sure this ConstantClass has already been visited (checked)! checkIndex(cc, cc.getNameIndex(), CONST_Utf8); - String cname = ((ConstantUtf8) cp.getConstant(cc.getNameIndex())).getBytes().replace('/','.'); + final String cname = ((ConstantUtf8) cp.getConstant(cc.getNameIndex())).getBytes().replace('/','.'); Verifier v = VerifierFactory.getVerifier(cname); VerificationResult vr = v.doPass1(); @@ -1006,8 +1006,8 @@ public final class Pass2Verifier extends PassVerifier implements Constants { // We cannot safely trust any other "instanceof" mechanism. We need to transitively verify // the ancestor hierarchy. JavaClass e = Repository.lookupClass(cname); - JavaClass t = Repository.lookupClass(Type.THROWABLE.getClassName()); - JavaClass o = Repository.lookupClass(Type.OBJECT.getClassName()); + final JavaClass t = Repository.lookupClass(Type.THROWABLE.getClassName()); + final JavaClass o = Repository.lookupClass(Type.OBJECT.getClassName()); while (e != o) { if (e == t) { break; // It's a subclass of Throwable, OKAY, leave. @@ -1035,7 +1035,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { // This is highly unelegant due to usage of the Visitor pattern. // TODO: rework it. int method_number = -1; - Method[] ms = Repository.lookupClass(myOwner.getClassName()).getMethods(); + final Method[] ms = Repository.lookupClass(myOwner.getClassName()).getMethods(); for (int mn=0; mn<ms.length; mn++) { if (m == ms[mn]) { method_number = mn; @@ -1050,7 +1050,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { int num_of_lvt_attribs = 0; // Now iterate through the attributes the Code attribute has. - Attribute[] atts = obj.getAttributes(); + final Attribute[] atts = obj.getAttributes(); for (int a=0; a<atts.length; a++) { if ((! (atts[a] instanceof LineNumberTable)) && (! (atts[a] instanceof LocalVariableTable))) { @@ -1068,41 +1068,41 @@ public final class Pass2Verifier extends PassVerifier implements Constants { //one certain Code attribute. if (atts[a] instanceof LocalVariableTable) { // checks conforming to vmspec2 4.7.9 - LocalVariableTable lvt = (LocalVariableTable) atts[a]; + final LocalVariableTable lvt = (LocalVariableTable) atts[a]; checkIndex(lvt, lvt.getNameIndex(), CONST_Utf8); - String lvtname = ((ConstantUtf8) cp.getConstant(lvt.getNameIndex())).getBytes(); + final String lvtname = ((ConstantUtf8) cp.getConstant(lvt.getNameIndex())).getBytes(); if (! lvtname.equals("LocalVariableTable")) { throw new ClassConstraintException("The LocalVariableTable attribute '"+tostring(lvt)+ "' is not correctly named 'LocalVariableTable' but '"+lvtname+"'."); } - Code code = obj; + final Code code = obj; //In JustIce, the check for correct offsets into the code array is delayed to Pass 3a. - LocalVariable[] localvariables = lvt.getLocalVariableTable(); + final LocalVariable[] localvariables = lvt.getLocalVariableTable(); - for (LocalVariable localvariable : localvariables) { + for (final LocalVariable localvariable : localvariables) { checkIndex(lvt, localvariable.getNameIndex(), CONST_Utf8); - String localname = ((ConstantUtf8) cp.getConstant(localvariable.getNameIndex())).getBytes(); + final String localname = ((ConstantUtf8) cp.getConstant(localvariable.getNameIndex())).getBytes(); if (!validJavaIdentifier(localname)) { throw new ClassConstraintException("LocalVariableTable '"+tostring(lvt)+ "' references a local variable by the name '"+localname+"' which is not a legal Java simple name."); } checkIndex(lvt, localvariable.getSignatureIndex(), CONST_Utf8); - String localsig = + final String localsig = ((ConstantUtf8) (cp.getConstant(localvariable.getSignatureIndex()))).getBytes(); // Local sig.(=descriptor) Type t; try{ t = Type.getType(localsig); } - catch (ClassFormatException cfe) { + catch (final ClassFormatException cfe) { throw new ClassConstraintException("Illegal descriptor (==signature) '"+localsig+ "' used by LocalVariable '"+tostring(localvariable)+"' referenced by '"+tostring(lvt)+"'.", cfe); } - int localindex = localvariable.getIndex(); + final int localindex = localvariable.getIndex(); if ( ( (t==Type.LONG || t==Type.DOUBLE)? localindex+1:localindex) >= code.getMaxLocals()) { throw new ClassConstraintException("LocalVariableTable attribute '"+tostring(lvt)+ "' references a LocalVariable '"+tostring(localvariable)+ @@ -1114,7 +1114,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { localVariablesInfos[method_number].add(localindex, localname, localvariable.getStartPC(), localvariable.getLength(), t); } - catch(LocalVariableInfoInconsistentException lviie) { + catch(final LocalVariableInfoInconsistentException lviie) { throw new ClassConstraintException("Conflicting information in LocalVariableTable '"+tostring(lvt)+ "' found in Code attribute '"+tostring(obj)+ "' (method '"+tostring(m)+"'). "+lviie.getMessage(), lviie); @@ -1130,7 +1130,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { }// if atts[a] instanceof LocalVariableTable END }// for all attributes atts[a] END - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: this might not be the best way to handle missing classes. throw new AssertionViolatedException("Missing class: " + e, e); } @@ -1143,21 +1143,21 @@ public final class Pass2Verifier extends PassVerifier implements Constants { // incorrectly named, it's the Exceptions attribute (vmspec2 4.7.4) checkIndex(obj, obj.getNameIndex(), CONST_Utf8); - String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); + final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); if (! name.equals("Exceptions")) { throw new ClassConstraintException( "The Exceptions attribute '"+tostring(obj)+"' is not correctly named 'Exceptions' but '"+name+"'."); } - int[] exc_indices = obj.getExceptionIndexTable(); + final int[] exc_indices = obj.getExceptionIndexTable(); - for (int exc_indice : exc_indices) { + for (final int exc_indice : exc_indices) { checkIndex(obj, exc_indice, CONST_Class); - ConstantClass cc = (ConstantClass) (cp.getConstant(exc_indice)); + final ConstantClass cc = (ConstantClass) (cp.getConstant(exc_indice)); checkIndex(cc, cc.getNameIndex(), CONST_Utf8); // can't be sure this ConstantClass has already been visited (checked)! //convert internal notation on-the-fly to external notation: - String cname = ((ConstantUtf8) cp.getConstant(cc.getNameIndex())).getBytes().replace('/','.'); + final String cname = ((ConstantUtf8) cp.getConstant(cc.getNameIndex())).getBytes().replace('/','.'); Verifier v = VerifierFactory.getVerifier(cname); VerificationResult vr = v.doPass1(); @@ -1169,8 +1169,8 @@ public final class Pass2Verifier extends PassVerifier implements Constants { // We cannot safely trust any other "instanceof" mechanism. We need to transitively verify // the ancestor hierarchy. JavaClass e = Repository.lookupClass(cname); - JavaClass t = Repository.lookupClass(Type.THROWABLE.getClassName()); - JavaClass o = Repository.lookupClass(Type.OBJECT.getClassName()); + final JavaClass t = Repository.lookupClass(Type.THROWABLE.getClassName()); + final JavaClass o = Repository.lookupClass(Type.OBJECT.getClassName()); while (e != o) { if (e == t) { break; // It's a subclass of Throwable, OKAY, leave. @@ -1191,7 +1191,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { } } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: this might not be the best way to handle missing classes. throw new AssertionViolatedException("Missing class: " + e, e); } @@ -1205,7 +1205,7 @@ public final class Pass2Verifier extends PassVerifier implements Constants { public void visitLineNumberTable(final LineNumberTable obj) {//vmspec2 4.7.8 checkIndex(obj, obj.getNameIndex(), CONST_Utf8); - String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); + final String name = ((ConstantUtf8) cp.getConstant(obj.getNameIndex())).getBytes(); if (! name.equals("LineNumberTable")) { throw new ClassConstraintException("The LineNumberTable attribute '"+tostring(obj)+ "' is not correctly named 'LineNumberTable' but '"+name+"'."); @@ -1286,11 +1286,11 @@ public final class Pass2Verifier extends PassVerifier implements Constants { */ private void field_and_method_refs_are_valid() { try { - JavaClass jc = Repository.lookupClass(myOwner.getClassName()); - DescendingVisitor v = new DescendingVisitor(jc, new FAMRAV_Visitor(jc)); + final JavaClass jc = Repository.lookupClass(myOwner.getClassName()); + final DescendingVisitor v = new DescendingVisitor(jc, new FAMRAV_Visitor(jc)); v.visit(); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: this might not be the best way to handle missing classes. throw new AssertionViolatedException("Missing class: " + e, e); } @@ -1316,26 +1316,26 @@ public final class Pass2Verifier extends PassVerifier implements Constants { if (obj.getTag() != Const.CONSTANT_Fieldref) { throw new ClassConstraintException("ConstantFieldref '"+tostring(obj)+"' has wrong tag!"); } - int name_and_type_index = obj.getNameAndTypeIndex(); - ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index)); - String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name + final int name_and_type_index = obj.getNameAndTypeIndex(); + final ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index)); + final String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name if (!validFieldName(name)) { throw new ClassConstraintException("Invalid field name '"+name+"' referenced by '"+tostring(obj)+"'."); } - int class_index = obj.getClassIndex(); - ConstantClass cc = (ConstantClass) (cp.getConstant(class_index)); - String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form + final int class_index = obj.getClassIndex(); + final ConstantClass cc = (ConstantClass) (cp.getConstant(class_index)); + final String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form if (! validClassName(className)) { throw new ClassConstraintException("Illegal class name '"+className+"' used by '"+tostring(obj)+"'."); } - String sig = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor) + final String sig = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor) try{ Type.getType(sig); /* Don't need the return value */ } - catch (ClassFormatException cfe) { + catch (final ClassFormatException cfe) { throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe); } } @@ -1345,30 +1345,30 @@ public final class Pass2Verifier extends PassVerifier implements Constants { if (obj.getTag() != Const.CONSTANT_Methodref) { throw new ClassConstraintException("ConstantMethodref '"+tostring(obj)+"' has wrong tag!"); } - int name_and_type_index = obj.getNameAndTypeIndex(); - ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index)); - String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name + final int name_and_type_index = obj.getNameAndTypeIndex(); + final ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index)); + final String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name if (!validClassMethodName(name)) { throw new ClassConstraintException( "Invalid (non-interface) method name '"+name+"' referenced by '"+tostring(obj)+"'."); } - int class_index = obj.getClassIndex(); - ConstantClass cc = (ConstantClass) (cp.getConstant(class_index)); - String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form + final int class_index = obj.getClassIndex(); + final ConstantClass cc = (ConstantClass) (cp.getConstant(class_index)); + final String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form if (! validClassName(className)) { throw new ClassConstraintException("Illegal class name '"+className+"' used by '"+tostring(obj)+"'."); } - String sig = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor) + final String sig = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor) try{ - Type t = Type.getReturnType(sig); + final Type t = Type.getReturnType(sig); if ( name.equals(Const.CONSTRUCTOR_NAME) && (t != Type.VOID) ) { throw new ClassConstraintException("Instance initialization method must have VOID return type."); } } - catch (ClassFormatException cfe) { + catch (final ClassFormatException cfe) { throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe); } } @@ -1378,31 +1378,31 @@ public final class Pass2Verifier extends PassVerifier implements Constants { if (obj.getTag() != Const.CONSTANT_InterfaceMethodref) { throw new ClassConstraintException("ConstantInterfaceMethodref '"+tostring(obj)+"' has wrong tag!"); } - int name_and_type_index = obj.getNameAndTypeIndex(); - ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index)); - String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name + final int name_and_type_index = obj.getNameAndTypeIndex(); + final ConstantNameAndType cnat = (ConstantNameAndType) (cp.getConstant(name_and_type_index)); + final String name = ((ConstantUtf8) (cp.getConstant(cnat.getNameIndex()))).getBytes(); // Field or Method name if (!validInterfaceMethodName(name)) { throw new ClassConstraintException("Invalid (interface) method name '"+name+"' referenced by '"+tostring(obj)+"'."); } - int class_index = obj.getClassIndex(); - ConstantClass cc = (ConstantClass) (cp.getConstant(class_index)); - String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form + final int class_index = obj.getClassIndex(); + final ConstantClass cc = (ConstantClass) (cp.getConstant(class_index)); + final String className = ((ConstantUtf8) (cp.getConstant(cc.getNameIndex()))).getBytes(); // Class Name in internal form if (! validClassName(className)) { throw new ClassConstraintException("Illegal class name '"+className+"' used by '"+tostring(obj)+"'."); } - String sig = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor) + final String sig = ((ConstantUtf8) (cp.getConstant(cnat.getSignatureIndex()))).getBytes(); // Field or Method sig.(=descriptor) try{ - Type t = Type.getReturnType(sig); + final Type t = Type.getReturnType(sig); if ( name.equals(Const.STATIC_INITIALIZER_NAME) && (t != Type.VOID) ) { addMessage("Class or interface initialization method '"+Const.STATIC_INITIALIZER_NAME+ "' usually has VOID return type instead of '"+t+ "'. Note this is really not a requirement of The Java Virtual Machine Specification, Second Edition."); } } - catch (ClassFormatException cfe) { + catch (final ClassFormatException cfe) { throw new ClassConstraintException("Illegal descriptor (==signature) '"+sig+"' used by '"+tostring(obj)+"'.", cfe); } @@ -1552,9 +1552,9 @@ public final class Pass2Verifier extends PassVerifier implements Constants { /** This method casually visits ConstantClass references. */ @Override public void visitConstantClass(final ConstantClass obj) { - Constant c = cp.getConstant(obj.getNameIndex()); + final Constant c = cp.getConstant(obj.getNameIndex()); if (c instanceof ConstantUtf8) { //Ignore the case where it's not a ConstantUtf8 here, we'll find out later. - String classname = ((ConstantUtf8) c).getBytes(); + final String classname = ((ConstantUtf8) c).getBytes(); if (classname.startsWith(jc.getClassName().replace('.','/')+"$")) { hasInnerClass = true; } diff --git a/src/main/java/org/apache/bcel/verifier/statics/Pass3aVerifier.java b/src/main/java/org/apache/bcel/verifier/statics/Pass3aVerifier.java index 46166fe0..f9d5f701 100644 --- a/src/main/java/org/apache/bcel/verifier/statics/Pass3aVerifier.java +++ b/src/main/java/org/apache/bcel/verifier/statics/Pass3aVerifier.java @@ -162,12 +162,12 @@ public final class Pass3aVerifier extends PassVerifier{ if (myOwner.doPass2().equals(VerificationResult.VR_OK)) { // Okay, class file was loaded correctly by Pass 1 // and satisfies static constraints of Pass 2. - JavaClass jc = Repository.lookupClass(myOwner.getClassName()); - Method[] methods = jc.getMethods(); + final JavaClass jc = Repository.lookupClass(myOwner.getClassName()); + final Method[] methods = jc.getMethods(); if (method_no >= methods.length) { throw new InvalidMethodException("METHOD DOES NOT EXIST!"); } - Method method = methods[method_no]; + final Method method = methods[method_no]; code = method.getCode(); // No Code? Nothing to verify! @@ -187,7 +187,7 @@ public final class Pass3aVerifier extends PassVerifier{ try{ instructionList = new InstructionList(method.getCode().getCode()); } - catch(RuntimeException re) { + catch(final RuntimeException re) { return new VerificationResult(VerificationResult.VERIFIED_REJECTED, "Bad bytecode in the code array of the Code attribute of method '"+method+"'."); } @@ -199,7 +199,7 @@ public final class Pass3aVerifier extends PassVerifier{ try{ delayedPass2Checks(); } - catch(ClassConstraintException cce) { + catch(final ClassConstraintException cce) { vr = new VerificationResult(VerificationResult.VERIFIED_REJECTED, cce.getMessage()); return vr; } @@ -207,17 +207,17 @@ public final class Pass3aVerifier extends PassVerifier{ pass3StaticInstructionChecks(); pass3StaticInstructionOperandsChecks(); } - catch(StaticCodeConstraintException scce) { + catch(final StaticCodeConstraintException scce) { vr = new VerificationResult(VerificationResult.VERIFIED_REJECTED, scce.getMessage()); } - catch(ClassCastException cce) { + catch(final ClassCastException cce) { vr = new VerificationResult(VerificationResult.VERIFIED_REJECTED, "Class Cast Exception: " + cce.getMessage()); } return vr; } //did not pass Pass 2. return VerificationResult.VR_NOTYET; - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -234,21 +234,21 @@ public final class Pass3aVerifier extends PassVerifier{ */ private void delayedPass2Checks() { - int[] instructionPositions = instructionList.getInstructionPositions(); - int codeLength = code.getCode().length; + final int[] instructionPositions = instructionList.getInstructionPositions(); + final int codeLength = code.getCode().length; ///////////////////// // LineNumberTable // ///////////////////// - LineNumberTable lnt = code.getLineNumberTable(); + final LineNumberTable lnt = code.getLineNumberTable(); if (lnt != null) { - LineNumber[] lineNumbers = lnt.getLineNumberTable(); - IntList offsets = new IntList(); + final LineNumber[] lineNumbers = lnt.getLineNumberTable(); + final IntList offsets = new IntList(); lineNumber_loop: - for (LineNumber lineNumber : lineNumbers) { // may appear in any order. - for (int instructionPosition : instructionPositions) { + for (final LineNumber lineNumber : lineNumbers) { // may appear in any order. + for (final int instructionPosition : instructionPositions) { // TODO: Make this a binary search! The instructionPositions array is naturally ordered! - int offset = lineNumber.getStartPC(); + final int offset = lineNumber.getStartPC(); if (instructionPosition == offset) { if (offsets.contains(offset)) { addMessage("LineNumberTable attribute '" + code.getLineNumberTable() + @@ -271,14 +271,14 @@ public final class Pass3aVerifier extends PassVerifier{ /////////////////////////// /* We cannot use code.getLocalVariableTable() because there could be more than only one. This is a bug in BCEL. */ - Attribute[] atts = code.getAttributes(); - for (Attribute att : atts) { + final Attribute[] atts = code.getAttributes(); + for (final Attribute att : atts) { if (att instanceof LocalVariableTable) { - LocalVariableTable lvt = (LocalVariableTable) att; - LocalVariable[] localVariables = lvt.getLocalVariableTable(); - for (LocalVariable localVariable : localVariables) { - int startpc = localVariable.getStartPC(); - int length = localVariable.getLength(); + final LocalVariableTable lvt = (LocalVariableTable) att; + final LocalVariable[] localVariables = lvt.getLocalVariableTable(); + for (final LocalVariable localVariable : localVariables) { + final int startpc = localVariable.getStartPC(); + final int length = localVariable.getLength(); if (!contains(instructionPositions, startpc)) { throw new ClassConstraintException("Code attribute '" + code @@ -301,11 +301,11 @@ public final class Pass3aVerifier extends PassVerifier{ // In BCEL's "classfile" API, the startPC/endPC-notation is // inclusive/exclusive as in the Java Virtual Machine Specification. // WARNING: This is not true for BCEL's "generic" API. - CodeException[] exceptionTable = code.getExceptionTable(); - for (CodeException element : exceptionTable) { - int startpc = element.getStartPC(); - int endpc = element.getEndPC(); - int handlerpc = element.getHandlerPC(); + final CodeException[] exceptionTable = code.getExceptionTable(); + for (final CodeException element : exceptionTable) { + final int startpc = element.getStartPC(); + final int endpc = element.getEndPC(); + final int handlerpc = element.getHandlerPC(); if (startpc >= endpc) { throw new ClassConstraintException("Code attribute '"+code+"' has an exception_table entry '"+element+ "' that has its start_pc ('"+startpc+"') not smaller than its end_pc ('"+endpc+"')."); @@ -362,7 +362,7 @@ public final class Pass3aVerifier extends PassVerifier{ // We currently go the safe way here. InstructionHandle ih = instructionList.getStart(); while (ih != null) { - Instruction i = ih.getInstruction(); + final Instruction i = ih.getInstruction(); if (i instanceof IMPDEP1) { throw new StaticCodeInstructionConstraintException( "IMPDEP1 must not be in the code, it is an illegal instruction for _internal_ JVM use!"); @@ -382,7 +382,7 @@ public final class Pass3aVerifier extends PassVerifier{ // An unreachable last instruction may also not fall through the // end of the code, which is stupid -- but with the original // verifier's subroutine semantics one cannot predict reachability. - Instruction last = instructionList.getEnd().getInstruction(); + final Instruction last = instructionList.getEnd().getInstruction(); if (! ((last instanceof ReturnInstruction) || (last instanceof RET) || (last instanceof GotoInstruction) || @@ -416,17 +416,17 @@ public final class Pass3aVerifier extends PassVerifier{ // TODO: Implement as much as possible here. BCEL does _not_ check everything. - ConstantPoolGen cpg = new ConstantPoolGen(Repository.lookupClass(myOwner.getClassName()).getConstantPool()); - InstOperandConstraintVisitor v = new InstOperandConstraintVisitor(cpg); + final ConstantPoolGen cpg = new ConstantPoolGen(Repository.lookupClass(myOwner.getClassName()).getConstantPool()); + final InstOperandConstraintVisitor v = new InstOperandConstraintVisitor(cpg); // Checks for the things BCEL does _not_ handle itself. InstructionHandle ih = instructionList.getStart(); while (ih != null) { - Instruction i = ih.getInstruction(); + final Instruction i = ih.getInstruction(); // An "own" constraint, due to JustIce's new definition of what "subroutine" means. if (i instanceof JsrInstruction) { - InstructionHandle target = ((JsrInstruction) i).getTarget(); + final InstructionHandle target = ((JsrInstruction) i).getTarget(); if (target == instructionList.getStart()) { throw new StaticCodeInstructionOperandConstraintException( "Due to JustIce's clear definition of subroutines, no JSR or JSR_W may have a top-level instruction"+ @@ -445,7 +445,7 @@ public final class Pass3aVerifier extends PassVerifier{ ih = ih.getNext(); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -453,7 +453,7 @@ public final class Pass3aVerifier extends PassVerifier{ /** A small utility method returning if a given int i is in the given int[] ints. */ private static boolean contains(final int[] ints, final int i) { - for (int k : ints) { + for (final int k : ints) { if (k==i) { return true; } @@ -486,7 +486,7 @@ public final class Pass3aVerifier extends PassVerifier{ private int max_locals() { try { return Repository.lookupClass(myOwner.getClassName()).getMethods()[method_no].getCode().getMaxLocals(); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -518,10 +518,10 @@ public final class Pass3aVerifier extends PassVerifier{ */ @Override public void visitLoadClass(final LoadClass o) { - ObjectType t = o.getLoadClassType(cpg); + final ObjectType t = o.getLoadClassType(cpg); if (t != null) {// null means "no class is loaded" - Verifier v = VerifierFactory.getVerifier(t.getClassName()); - VerificationResult vr = v.doPass1(); + final Verifier v = VerifierFactory.getVerifier(t.getClassName()); + final VerificationResult vr = v.doPass1(); if (vr.getStatus() != VerificationResult.VERIFIED_OK) { constraintViolated((Instruction) o, "Class '"+o.getLoadClassType(cpg).getClassName()+"' is referenced, but cannot be loaded: '"+vr+"'."); @@ -541,7 +541,7 @@ public final class Pass3aVerifier extends PassVerifier{ @Override public void visitLDC(final LDC o) { indexValid(o, o.getIndex()); - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (c instanceof ConstantClass) { addMessage("Operand of LDC or LDC_W is CONSTANT_Class '"+c+"' - this is only supported in JDK 1.5 and higher."); } @@ -560,7 +560,7 @@ public final class Pass3aVerifier extends PassVerifier{ @Override public void visitLDC2_W(final LDC2_W o) { indexValid(o, o.getIndex()); - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! ( (c instanceof ConstantLong) || (c instanceof ConstantDouble) ) ) { constraintViolated(o, "Operand of LDC2_W must be CONSTANT_Long or CONSTANT_Double, but is '"+c+"'."); @@ -568,13 +568,13 @@ public final class Pass3aVerifier extends PassVerifier{ try{ indexValid(o, o.getIndex()+1); } - catch(StaticCodeInstructionOperandConstraintException e) { + catch(final StaticCodeInstructionOperandConstraintException e) { throw new AssertionViolatedException("OOPS: Does not BCEL handle that? LDC2_W operand has a problem.", e); } } private ObjectType getObjectType(final FieldInstruction o) { - ReferenceType rt = o.getReferenceType(cpg); + final ReferenceType rt = o.getReferenceType(cpg); if(rt instanceof ObjectType) { return (ObjectType)rt; } @@ -588,20 +588,20 @@ public final class Pass3aVerifier extends PassVerifier{ public void visitFieldInstruction(final FieldInstruction o) { try { indexValid(o, o.getIndex()); - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantFieldref)) { constraintViolated(o, "Indexing a constant that's not a CONSTANT_Fieldref but a '"+c+"'."); } - String field_name = o.getFieldName(cpg); + final String field_name = o.getFieldName(cpg); - JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); + final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); Field[] fields = jc.getFields(); Field f = null; - for (Field field : fields) { + for (final Field field : fields) { if (field.getName().equals(field_name)) { - Type f_type = Type.getType(field.getSignature()); - Type o_type = o.getType(cpg); + final Type f_type = Type.getType(field.getSignature()); + final Type o_type = o.getType(cpg); /* TODO: Check if assignment compatibility is sufficient. * What does Sun do? */ @@ -612,14 +612,14 @@ public final class Pass3aVerifier extends PassVerifier{ } } if (f == null) { - JavaClass[] superclasses = jc.getSuperClasses(); + final JavaClass[] superclasses = jc.getSuperClasses(); outer: - for (JavaClass superclass : superclasses) { + for (final JavaClass superclass : superclasses) { fields = superclass.getFields(); - for (Field field : fields) { + for (final Field field : fields) { if (field.getName().equals(field_name)) { - Type f_type = Type.getType(field.getSignature()); - Type o_type = o.getType(cpg); + final Type f_type = Type.getType(field.getSignature()); + final Type o_type = o.getType(cpg); if (f_type.equals(o_type)) { f = field; if ((f.getAccessFlags() & (Const.ACC_PUBLIC | Const.ACC_PROTECTED)) == 0) { @@ -651,7 +651,7 @@ public final class Pass3aVerifier extends PassVerifier{ /* TODO: Check for access modifiers here. */ } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -664,14 +664,14 @@ public final class Pass3aVerifier extends PassVerifier{ if ( (o instanceof INVOKEVIRTUAL) || (o instanceof INVOKESPECIAL) || (o instanceof INVOKESTATIC) ) { - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantMethodref)) { constraintViolated(o, "Indexing a constant that's not a CONSTANT_Methodref but a '"+c+"'."); } else{ // Constants are okay due to pass2. - ConstantNameAndType cnat = (ConstantNameAndType) (cpg.getConstant(((ConstantMethodref) c).getNameAndTypeIndex())); - ConstantUtf8 cutf8 = (ConstantUtf8) (cpg.getConstant(cnat.getNameIndex())); + final ConstantNameAndType cnat = (ConstantNameAndType) (cpg.getConstant(((ConstantMethodref) c).getNameAndTypeIndex())); + final ConstantUtf8 cutf8 = (ConstantUtf8) (cpg.getConstant(cnat.getNameIndex())); if (cutf8.getBytes().equals(Const.CONSTRUCTOR_NAME) && (!(o instanceof INVOKESPECIAL)) ) { constraintViolated(o, "Only INVOKESPECIAL is allowed to invoke instance initialization methods."); } @@ -683,7 +683,7 @@ public final class Pass3aVerifier extends PassVerifier{ } } else{ //if (o instanceof INVOKEINTERFACE) { - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantInterfaceMethodref)) { constraintViolated(o, "Indexing a constant that's not a CONSTANT_InterfaceMethodref but a '"+c+"'."); } @@ -693,9 +693,9 @@ public final class Pass3aVerifier extends PassVerifier{ // By now, BCEL hides those two operands because they're superfluous. // Invoked method must not be <init> or <clinit> - ConstantNameAndType cnat = + final ConstantNameAndType cnat = (ConstantNameAndType) (cpg.getConstant(((ConstantInterfaceMethodref)c).getNameAndTypeIndex())); - String name = ((ConstantUtf8) (cpg.getConstant(cnat.getNameIndex()))).getBytes(); + final String name = ((ConstantUtf8) (cpg.getConstant(cnat.getNameIndex()))).getBytes(); if (name.equals(Const.CONSTRUCTOR_NAME)) { constraintViolated(o, "Method to invoke must not be '"+Const.CONSTRUCTOR_NAME+"'."); } @@ -711,22 +711,22 @@ public final class Pass3aVerifier extends PassVerifier{ t = ((ArrayType) t).getBasicType(); } if (t instanceof ObjectType) { - Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName()); - VerificationResult vr = v.doPass2(); + final Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName()); + final VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK) { constraintViolated(o, "Return type class/interface could not be verified successfully: '"+vr.getMessage()+"'."); } } - Type[] ts = o.getArgumentTypes(cpg); - for (Type element : ts) { + final Type[] ts = o.getArgumentTypes(cpg); + for (final Type element : ts) { t = element; if (t instanceof ArrayType) { t = ((ArrayType) t).getBasicType(); } if (t instanceof ObjectType) { - Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName()); - VerificationResult vr = v.doPass2(); + final Verifier v = VerifierFactory.getVerifier(((ObjectType) t).getClassName()); + final VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK) { constraintViolated(o, "Argument type class/interface could not be verified successfully: '"+vr.getMessage()+"'."); @@ -740,7 +740,7 @@ public final class Pass3aVerifier extends PassVerifier{ @Override public void visitINSTANCEOF(final INSTANCEOF o) { indexValid(o, o.getIndex()); - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)) { constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } @@ -750,7 +750,7 @@ public final class Pass3aVerifier extends PassVerifier{ @Override public void visitCHECKCAST(final CHECKCAST o) { indexValid(o, o.getIndex()); - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)) { constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } @@ -760,13 +760,13 @@ public final class Pass3aVerifier extends PassVerifier{ @Override public void visitNEW(final NEW o) { indexValid(o, o.getIndex()); - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)) { constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } else{ - ConstantUtf8 cutf8 = (ConstantUtf8) (cpg.getConstant( ((ConstantClass) c).getNameIndex() )); - Type t = Type.getType("L"+cutf8.getBytes()+";"); + final ConstantUtf8 cutf8 = (ConstantUtf8) (cpg.getConstant( ((ConstantClass) c).getNameIndex() )); + final Type t = Type.getType("L"+cutf8.getBytes()+";"); if (t instanceof ArrayType) { constraintViolated(o, "NEW must not be used to create an array."); } @@ -778,17 +778,17 @@ public final class Pass3aVerifier extends PassVerifier{ @Override public void visitMULTIANEWARRAY(final MULTIANEWARRAY o) { indexValid(o, o.getIndex()); - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)) { constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } - int dimensions2create = o.getDimensions(); + final int dimensions2create = o.getDimensions(); if (dimensions2create < 1) { constraintViolated(o, "Number of dimensions to create must be greater than zero."); } - Type t = o.getType(cpg); + final Type t = o.getType(cpg); if (t instanceof ArrayType) { - int dimensions = ((ArrayType) t).getDimensions(); + final int dimensions = ((ArrayType) t).getDimensions(); if (dimensions < dimensions2create) { constraintViolated(o, "Not allowed to create array with more dimensions ('"+dimensions2create+ @@ -805,13 +805,13 @@ public final class Pass3aVerifier extends PassVerifier{ @Override public void visitANEWARRAY(final ANEWARRAY o) { indexValid(o, o.getIndex()); - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)) { constraintViolated(o, "Expecting a CONSTANT_Class operand, but found a '"+c+"'."); } - Type t = o.getType(cpg); + final Type t = o.getType(cpg); if (t instanceof ArrayType) { - int dimensions = ((ArrayType) t).getDimensions(); + final int dimensions = ((ArrayType) t).getDimensions(); if (dimensions > Const.MAX_ARRAY_DIMENSIONS) { constraintViolated(o, "Not allowed to create an array with more than "+ Const.MAX_ARRAY_DIMENSIONS + " dimensions;"+ @@ -823,7 +823,7 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitNEWARRAY(final NEWARRAY o) { - byte t = o.getTypecode(); + final byte t = o.getTypecode(); if (! ( (t == Const.T_BOOLEAN) || (t == Const.T_CHAR) || (t == Const.T_FLOAT) || @@ -839,12 +839,12 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitILOAD(final ILOAD o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ - int maxminus1 = max_locals()-1; + final int maxminus1 = max_locals()-1; if (idx > maxminus1) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } @@ -854,12 +854,12 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitFLOAD(final FLOAD o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ - int maxminus1 = max_locals()-1; + final int maxminus1 = max_locals()-1; if (idx > maxminus1) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } @@ -869,12 +869,12 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitALOAD(final ALOAD o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ - int maxminus1 = max_locals()-1; + final int maxminus1 = max_locals()-1; if (idx > maxminus1) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } @@ -884,12 +884,12 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitISTORE(final ISTORE o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ - int maxminus1 = max_locals()-1; + final int maxminus1 = max_locals()-1; if (idx > maxminus1) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } @@ -899,12 +899,12 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitFSTORE(final FSTORE o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ - int maxminus1 = max_locals()-1; + final int maxminus1 = max_locals()-1; if (idx > maxminus1) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } @@ -914,12 +914,12 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitASTORE(final ASTORE o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ - int maxminus1 = max_locals()-1; + final int maxminus1 = max_locals()-1; if (idx > maxminus1) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } @@ -929,12 +929,12 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitIINC(final IINC o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ - int maxminus1 = max_locals()-1; + final int maxminus1 = max_locals()-1; if (idx > maxminus1) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } @@ -944,12 +944,12 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitRET(final RET o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."); } else{ - int maxminus1 = max_locals()-1; + final int maxminus1 = max_locals()-1; if (idx > maxminus1) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-1 '"+maxminus1+"'."); } @@ -959,13 +959,13 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitLLOAD(final LLOAD o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."+ " [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ - int maxminus2 = max_locals()-2; + final int maxminus2 = max_locals()-2; if (idx > maxminus2) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } @@ -975,13 +975,13 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitDLOAD(final DLOAD o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."+ " [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ - int maxminus2 = max_locals()-2; + final int maxminus2 = max_locals()-2; if (idx > maxminus2) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } @@ -991,13 +991,13 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitLSTORE(final LSTORE o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."+ " [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ - int maxminus2 = max_locals()-2; + final int maxminus2 = max_locals()-2; if (idx > maxminus2) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } @@ -1007,13 +1007,13 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitDSTORE(final DSTORE o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if (idx < 0) { constraintViolated(o, "Index '"+idx+"' must be non-negative."+ " [Constraint by JustIce as an analogon to the single-slot xLOAD/xSTORE instructions; may not happen anyway.]"); } else{ - int maxminus2 = max_locals()-2; + final int maxminus2 = max_locals()-2; if (idx > maxminus2) { constraintViolated(o, "Index '"+idx+"' must not be greater than max_locals-2 '"+maxminus2+"'."); } @@ -1023,7 +1023,7 @@ public final class Pass3aVerifier extends PassVerifier{ /** Checks if the constraints of operands of the said instruction(s) are satisfied. */ @Override public void visitLOOKUPSWITCH(final LOOKUPSWITCH o) { - int[] matchs = o.getMatchs(); + final int[] matchs = o.getMatchs(); int max = Integer.MIN_VALUE; for (int i=0; i<matchs.length; i++) { if (matchs[i] == max && i != 0) { @@ -1049,11 +1049,11 @@ public final class Pass3aVerifier extends PassVerifier{ @Override public void visitPUTSTATIC(final PUTSTATIC o) { try { - String field_name = o.getFieldName(cpg); - JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); - Field[] fields = jc.getFields(); + final String field_name = o.getFieldName(cpg); + final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); + final Field[] fields = jc.getFields(); Field f = null; - for (Field field : fields) { + for (final Field field : fields) { if (field.getName().equals(field_name)) { f = field; break; @@ -1075,13 +1075,13 @@ public final class Pass3aVerifier extends PassVerifier{ constraintViolated(o, "Referenced field '"+f+"' is not static which it should be."); } - String meth_name = Repository.lookupClass(myOwner.getClassName()).getMethods()[method_no].getName(); + final String meth_name = Repository.lookupClass(myOwner.getClassName()).getMethods()[method_no].getName(); // If it's an interface, it can be set only in <clinit>. if ((!(jc.isClass())) && (!(meth_name.equals(Const.STATIC_INITIALIZER_NAME)))) { constraintViolated(o, "Interface field '"+f+"' must be set in a '"+Const.STATIC_INITIALIZER_NAME+"' method."); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -1091,11 +1091,11 @@ public final class Pass3aVerifier extends PassVerifier{ @Override public void visitGETSTATIC(final GETSTATIC o) { try { - String field_name = o.getFieldName(cpg); - JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); - Field[] fields = jc.getFields(); + final String field_name = o.getFieldName(cpg); + final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); + final Field[] fields = jc.getFields(); Field f = null; - for (Field field : fields) { + for (final Field field : fields) { if (field.getName().equals(field_name)) { f = field; break; @@ -1108,7 +1108,7 @@ public final class Pass3aVerifier extends PassVerifier{ if (! (f.isStatic())) { constraintViolated(o, "Referenced field '"+f+"' is not static which it should be."); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -1138,9 +1138,9 @@ public final class Pass3aVerifier extends PassVerifier{ // is therefore resolved/verified. // INVOKEINTERFACE is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. - String classname = o.getClassName(cpg); - JavaClass jc = Repository.lookupClass(classname); - Method m = getMethodRecursive(jc, o); + final String classname = o.getClassName(cpg); + final JavaClass jc = Repository.lookupClass(classname); + final Method m = getMethodRecursive(jc, o); if (m == null) { constraintViolated(o, "Referenced method '"+o.getMethodName(cpg)+"' with expected signature '"+o.getSignature(cpg)+ "' not found in class '"+jc.getClassName()+"'."); @@ -1148,7 +1148,7 @@ public final class Pass3aVerifier extends PassVerifier{ if (jc.isClass()) { constraintViolated(o, "Referenced class '"+jc.getClassName()+"' is a class, but not an interface as expected."); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -1170,7 +1170,7 @@ public final class Pass3aVerifier extends PassVerifier{ return m; } //method not found, look in super classes - for (JavaClass superclass : jc.getSuperClasses()) { + for (final JavaClass superclass : jc.getSuperClasses()) { m = getMethod(superclass, invoke); if(m != null) { //method found in super class @@ -1178,7 +1178,7 @@ public final class Pass3aVerifier extends PassVerifier{ } } //method not found, look in super interfaces - for (JavaClass superclass : jc.getInterfaces()) { + for (final JavaClass superclass : jc.getInterfaces()) { m = getMethod(superclass, invoke); if(m != null) { //method found in super interface @@ -1195,8 +1195,8 @@ public final class Pass3aVerifier extends PassVerifier{ * @return the referenced method or null if not found. */ private Method getMethod(final JavaClass jc, final InvokeInstruction invoke) { - Method[] ms = jc.getMethods(); - for (Method element : ms) { + final Method[] ms = jc.getMethods(); + for (final Method element : ms) { if ( (element.getName().equals(invoke.getMethodName(cpg))) && (Type.getReturnType(element.getSignature()).equals(invoke.getReturnType(cpg))) && (objarrayequals(Type.getArgumentTypes(element.getSignature()), invoke.getArgumentTypes(cpg))) ) { @@ -1215,9 +1215,9 @@ public final class Pass3aVerifier extends PassVerifier{ // is therefore resolved/verified. // INVOKESPECIAL is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. - String classname = o.getClassName(cpg); - JavaClass jc = Repository.lookupClass(classname); - Method m = getMethodRecursive(jc, o); + final String classname = o.getClassName(cpg); + final JavaClass jc = Repository.lookupClass(classname); + final Method m = getMethodRecursive(jc, o); if (m == null) { constraintViolated(o, "Referenced method '"+o.getMethodName(cpg)+"' with expected signature '"+o.getSignature(cpg) +"' not found in class '"+jc.getClassName()+"'."); @@ -1238,8 +1238,8 @@ public final class Pass3aVerifier extends PassVerifier{ supidx = current.getSuperclassNameIndex(); current = Repository.lookupClass(current.getSuperclassName()); - Method[] meths = current.getMethods(); - for (Method meth2 : meths) { + final Method[] meths = current.getMethods(); + for (final Method meth2 : meths) { if ( (meth2.getName().equals(o.getMethodName(cpg))) && (Type.getReturnType(meth2.getSignature()).equals(o.getReturnType(cpg))) && (objarrayequals(Type.getArgumentTypes(meth2.getSignature()), o.getArgumentTypes(cpg))) ) { @@ -1259,7 +1259,7 @@ public final class Pass3aVerifier extends PassVerifier{ } } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -1274,9 +1274,9 @@ public final class Pass3aVerifier extends PassVerifier{ // is therefore resolved/verified. // INVOKESTATIC is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. - String classname = o.getClassName(cpg); - JavaClass jc = Repository.lookupClass(classname); - Method m = getMethodRecursive(jc, o); + final String classname = o.getClassName(cpg); + final JavaClass jc = Repository.lookupClass(classname); + final Method m = getMethodRecursive(jc, o); if (m == null) { constraintViolated(o, "Referenced method '"+o.getMethodName(cpg)+"' with expected signature '"+ o.getSignature(cpg) +"' not found in class '"+jc.getClassName()+"'."); @@ -1284,7 +1284,7 @@ public final class Pass3aVerifier extends PassVerifier{ constraintViolated(o, "Referenced method '"+o.getMethodName(cpg)+"' has ACC_STATIC unset."); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -1299,9 +1299,9 @@ public final class Pass3aVerifier extends PassVerifier{ // is therefore resolved/verified. // INVOKEVIRTUAL is an InvokeInstruction, the argument and return types are resolved/verified, // too. So are the allowed method names. - String classname = o.getClassName(cpg); - JavaClass jc = Repository.lookupClass(classname); - Method m = getMethodRecursive(jc, o); + final String classname = o.getClassName(cpg); + final JavaClass jc = Repository.lookupClass(classname); + final Method m = getMethodRecursive(jc, o); if (m == null) { constraintViolated(o, "Referenced method '"+o.getMethodName(cpg)+"' with expected signature '"+ o.getSignature(cpg)+"' not found in class '"+jc.getClassName()+"'."); @@ -1310,7 +1310,7 @@ public final class Pass3aVerifier extends PassVerifier{ constraintViolated(o, "Referenced class '"+jc.getClassName()+"' is an interface, but not a class as expected."); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } diff --git a/src/main/java/org/apache/bcel/verifier/statics/StringRepresentation.java b/src/main/java/org/apache/bcel/verifier/statics/StringRepresentation.java index 31b6367a..06505c63 100644 --- a/src/main/java/org/apache/bcel/verifier/statics/StringRepresentation.java +++ b/src/main/java/org/apache/bcel/verifier/statics/StringRepresentation.java @@ -123,7 +123,7 @@ public class StringRepresentation extends org.apache.bcel.classfile.EmptyVisitor ret = obj.toString(); } - catch (RuntimeException e) { + catch (final RuntimeException e) { // including ClassFormatException, trying to convert the "signature" of a ReturnaddressType LocalVariable // (shouldn't occur, but people do crazy things) String s = obj.getClass().getName(); diff --git a/src/main/java/org/apache/bcel/verifier/structurals/ControlFlowGraph.java b/src/main/java/org/apache/bcel/verifier/structurals/ControlFlowGraph.java index c6b58e10..ae4d48a5 100644 --- a/src/main/java/org/apache/bcel/verifier/structurals/ControlFlowGraph.java +++ b/src/main/java/org/apache/bcel/verifier/structurals/ControlFlowGraph.java @@ -122,7 +122,7 @@ public class ControlFlowGraph{ Frame org; - InstructionContext jsr = lastExecutionJSR(); + final InstructionContext jsr = lastExecutionJSR(); org = outFrames.get(jsr); @@ -137,7 +137,7 @@ public class ControlFlowGraph{ public Frame getInFrame() { Frame org; - InstructionContext jsr = lastExecutionJSR(); + final InstructionContext jsr = lastExecutionJSR(); org = inFrames.get(jsr); @@ -194,7 +194,7 @@ public class ControlFlowGraph{ // Now we're sure the inFrame has changed! // new inFrame is already merged in, see above. - Frame workingFrame = inF.getClone(); + final Frame workingFrame = inF.getClone(); try{ // This verifies the InstructionConstraint for the current @@ -203,7 +203,7 @@ public class ControlFlowGraph{ icv.setFrame(workingFrame); getInstruction().accept(icv); } - catch(StructuralCodeConstraintException ce) { + catch(final StructuralCodeConstraintException ce) { ce.extendMessage("","\nInstructionHandle: "+getInstruction()+"\n"); ce.extendMessage("","\nExecution Frame:\n"+workingFrame); extendMessageWithFlow(ce); @@ -230,7 +230,7 @@ public class ControlFlowGraph{ //TODO: Put information in the brackets, e.g. // Is this an ExceptionHandler? Is this a RET? Is this the start of // a subroutine? - String ret = getInstruction().toString(false)+"\t[InstructionContext]"; + final String ret = getInstruction().toString(false)+"\t[InstructionContext]"; return ret; } @@ -240,13 +240,13 @@ public class ControlFlowGraph{ */ private boolean mergeInFrames(final Frame inFrame) { // TODO: Can be performance-improved. - Frame inF = inFrames.get(lastExecutionJSR()); - OperandStack oldstack = inF.getStack().getClone(); - LocalVariables oldlocals = inF.getLocals().getClone(); + final Frame inF = inFrames.get(lastExecutionJSR()); + final OperandStack oldstack = inF.getStack().getClone(); + final LocalVariables oldlocals = inF.getLocals().getClone(); try { inF.getStack().merge(inFrame.getStack()); inF.getLocals().merge(inFrame.getLocals()); - } catch (StructuralCodeConstraintException sce) { + } catch (final StructuralCodeConstraintException sce) { extendMessageWithFlow(sce); throw sce; } @@ -273,7 +273,7 @@ public class ControlFlowGraph{ * violation that triggered the throwing of the "e" object. */ private void extendMessageWithFlow(final StructuralCodeConstraintException e) { - String s = "Execution flow:\n"; + final String s = "Execution flow:\n"; e.extendMessage("", s+getExecutionChain()); } @@ -294,12 +294,12 @@ public class ControlFlowGraph{ */ private InstructionContextImpl lastExecutionJSR() { - int size = executionPredecessors.size(); + final int size = executionPredecessors.size(); int retcount = 0; for (int i=size-1; i>=0; i--) { - InstructionContextImpl current = (InstructionContextImpl) (executionPredecessors.get(i)); - Instruction currentlast = current.getInstruction().getInstruction(); + final InstructionContextImpl current = (InstructionContextImpl) (executionPredecessors.get(i)); + final Instruction currentlast = current.getInstruction().getInstruction(); if (currentlast instanceof RET) { retcount++; } @@ -330,10 +330,10 @@ public class ControlFlowGraph{ final InstructionHandle[] empty = new InstructionHandle[0]; final InstructionHandle[] single = new InstructionHandle[1]; - Instruction inst = getInstruction().getInstruction(); + final Instruction inst = getInstruction().getInstruction(); if (inst instanceof RET) { - Subroutine s = subroutines.subroutineOf(getInstruction()); + final Subroutine s = subroutines.subroutineOf(getInstruction()); if (s==null) { //return empty; // RET in dead code. "empty" would be the correct answer, but we know something about the surrounding project... throw new AssertionViolatedException("Asking for successors of a RET in dead code?!"); @@ -343,8 +343,8 @@ public class ControlFlowGraph{ // will want it. Thanks Johannes Wust. //throw new AssertionViolatedException("DID YOU REALLY WANT TO ASK FOR RET'S SUCCS?"); - InstructionHandle[] jsrs = s.getEnteringJsrInstructions(); - InstructionHandle[] ret = new InstructionHandle[jsrs.length]; + final InstructionHandle[] jsrs = s.getEnteringJsrInstructions(); + final InstructionHandle[] ret = new InstructionHandle[jsrs.length]; for (int i=0; i<jsrs.length; i++) { ret[i] = jsrs[i].getNext(); } @@ -377,8 +377,8 @@ public class ControlFlowGraph{ if (inst instanceof Select) { // BCEL's getTargets() returns only the non-default targets, // thanks to Eli Tilevich for reporting. - InstructionHandle[] matchTargets = ((Select) inst).getTargets(); - InstructionHandle[] ret = new InstructionHandle[matchTargets.length+1]; + final InstructionHandle[] matchTargets = ((Select) inst).getTargets(); + final InstructionHandle[] ret = new InstructionHandle[matchTargets.length+1]; ret[0] = ((Select) inst).getTarget(); System.arraycopy(matchTargets, 0, ret, 1, matchTargets.length); return ret; @@ -426,8 +426,8 @@ public class ControlFlowGraph{ subroutines = new Subroutines(method_gen, enableJustIceCheck); exceptionhandlers = new ExceptionHandlers(method_gen); - InstructionHandle[] instructionhandles = method_gen.getInstructionList().getInstructionHandles(); - for (InstructionHandle instructionhandle : instructionhandles) { + final InstructionHandle[] instructionhandles = method_gen.getInstructionList().getInstructionHandles(); + for (final InstructionHandle instructionhandle : instructionhandles) { instructionContexts.put(instructionhandle, new InstructionContextImpl(instructionhandle)); } @@ -438,7 +438,7 @@ public class ControlFlowGraph{ * Returns the InstructionContext of a given instruction. */ public InstructionContext contextOf(final InstructionHandle inst) { - InstructionContext ic = instructionContexts.get(inst); + final InstructionContext ic = instructionContexts.get(inst); if (ic == null) { throw new AssertionViolatedException("InstructionContext requested for an InstructionHandle that's not known!"); } @@ -450,7 +450,7 @@ public class ControlFlowGraph{ * in a naturally ordered manner. */ public InstructionContext[] contextsOf(final InstructionHandle[] insts) { - InstructionContext[] ret = new InstructionContext[insts.length]; + final InstructionContext[] ret = new InstructionContext[insts.length]; for (int i=0; i<insts.length; i++) { ret[i] = contextOf(insts[i]); } @@ -463,7 +463,7 @@ public class ControlFlowGraph{ * <B>(NOT ORDERED!)</B>. */ public InstructionContext[] getInstructionContexts() { - InstructionContext[] ret = new InstructionContext[instructionContexts.values().size()]; + final InstructionContext[] ret = new InstructionContext[instructionContexts.values().size()]; return instructionContexts.values().toArray(ret); } diff --git a/src/main/java/org/apache/bcel/verifier/structurals/ExceptionHandlers.java b/src/main/java/org/apache/bcel/verifier/structurals/ExceptionHandlers.java index 47a0895d..84820eff 100644 --- a/src/main/java/org/apache/bcel/verifier/structurals/ExceptionHandlers.java +++ b/src/main/java/org/apache/bcel/verifier/structurals/ExceptionHandlers.java @@ -44,9 +44,9 @@ public class ExceptionHandlers{ */ public ExceptionHandlers(final MethodGen mg) { exceptionhandlers = new HashMap<>(); - CodeExceptionGen[] cegs = mg.getExceptionHandlers(); - for (CodeExceptionGen ceg : cegs) { - ExceptionHandler eh = new ExceptionHandler(ceg.getCatchType(), ceg.getHandlerPC()); + final CodeExceptionGen[] cegs = mg.getExceptionHandlers(); + for (final CodeExceptionGen ceg : cegs) { + final ExceptionHandler eh = new ExceptionHandler(ceg.getCatchType(), ceg.getHandlerPC()); for (InstructionHandle ih=ceg.getStartPC(); ih != ceg.getEndPC().getNext(); ih=ih.getNext()) { Set<ExceptionHandler> hs; hs = exceptionhandlers.get(ih); @@ -64,7 +64,7 @@ public class ExceptionHandlers{ * handlers that protect the instruction ih. */ public ExceptionHandler[] getExceptionHandlers(final InstructionHandle ih) { - Set<ExceptionHandler> hsSet = exceptionhandlers.get(ih); + final Set<ExceptionHandler> hsSet = exceptionhandlers.get(ih); if (hsSet == null) { return new ExceptionHandler[0]; } diff --git a/src/main/java/org/apache/bcel/verifier/structurals/ExecutionVisitor.java b/src/main/java/org/apache/bcel/verifier/structurals/ExecutionVisitor.java index fcb74f02..2bfd0922 100644 --- a/src/main/java/org/apache/bcel/verifier/structurals/ExecutionVisitor.java +++ b/src/main/java/org/apache/bcel/verifier/structurals/ExecutionVisitor.java @@ -125,12 +125,12 @@ public class ExecutionVisitor extends EmptyVisitor{ public void visitAALOAD(final AALOAD o) { stack().pop(); // pop the index int //System.out.print(stack().peek()); - Type t = stack().pop(); // Pop Array type + final Type t = stack().pop(); // Pop Array type if (t == Type.NULL) { stack().push(Type.NULL); } // Do nothing stackwise --- a NullPointerException is thrown at Run-Time else{ - ArrayType at = (ArrayType) t; + final ArrayType at = (ArrayType) t; stack().push(at.getElementType()); } } @@ -179,7 +179,7 @@ public class ExecutionVisitor extends EmptyVisitor{ /** Symbolically executes the corresponding Java Virtual Machine instruction. */ @Override public void visitATHROW(final ATHROW o) { - Type t = stack().pop(); + final Type t = stack().pop(); stack().clear(); if (t.equals(Type.NULL)) { stack().push(Type.getType("Ljava/lang/NullPointerException;")); @@ -347,15 +347,15 @@ public class ExecutionVisitor extends EmptyVisitor{ /** Symbolically executes the corresponding Java Virtual Machine instruction. */ @Override public void visitDUP(final DUP o) { - Type t = stack().pop(); + final Type t = stack().pop(); stack().push(t); stack().push(t); } /** Symbolically executes the corresponding Java Virtual Machine instruction. */ @Override public void visitDUP_X1(final DUP_X1 o) { - Type w1 = stack().pop(); - Type w2 = stack().pop(); + final Type w1 = stack().pop(); + final Type w2 = stack().pop(); stack().push(w1); stack().push(w2); stack().push(w1); @@ -363,15 +363,15 @@ public class ExecutionVisitor extends EmptyVisitor{ /** Symbolically executes the corresponding Java Virtual Machine instruction. */ @Override public void visitDUP_X2(final DUP_X2 o) { - Type w1 = stack().pop(); - Type w2 = stack().pop(); + final Type w1 = stack().pop(); + final Type w2 = stack().pop(); if (w2.getSize() == 2) { stack().push(w1); stack().push(w2); stack().push(w1); } else{ - Type w3 = stack().pop(); + final Type w3 = stack().pop(); stack().push(w1); stack().push(w3); stack().push(w2); @@ -381,13 +381,13 @@ public class ExecutionVisitor extends EmptyVisitor{ /** Symbolically executes the corresponding Java Virtual Machine instruction. */ @Override public void visitDUP2(final DUP2 o) { - Type t = stack().pop(); + final Type t = stack().pop(); if (t.getSize() == 2) { stack().push(t); stack().push(t); } else{ // t.getSize() is 1 - Type u = stack().pop(); + final Type u = stack().pop(); stack().push(u); stack().push(t); stack().push(u); @@ -397,16 +397,16 @@ public class ExecutionVisitor extends EmptyVisitor{ /** Symbolically executes the corresponding Java Virtual Machine instruction. */ @Override public void visitDUP2_X1(final DUP2_X1 o) { - Type t = stack().pop(); + final Type t = stack().pop(); if (t.getSize() == 2) { - Type u = stack().pop(); + final Type u = stack().pop(); stack().push(t); stack().push(u); stack().push(t); } else{ //t.getSize() is1 - Type u = stack().pop(); - Type v = stack().pop(); + final Type u = stack().pop(); + final Type v = stack().pop(); stack().push(u); stack().push(t); stack().push(v); @@ -417,15 +417,15 @@ public class ExecutionVisitor extends EmptyVisitor{ /** Symbolically executes the corresponding Java Virtual Machine instruction. */ @Override public void visitDUP2_X2(final DUP2_X2 o) { - Type t = stack().pop(); + final Type t = stack().pop(); if (t.getSize() == 2) { - Type u = stack().pop(); + final Type u = stack().pop(); if (u.getSize() == 2) { stack().push(t); stack().push(u); stack().push(t); }else{ - Type v = stack().pop(); + final Type v = stack().pop(); stack().push(t); stack().push(v); stack().push(u); @@ -433,8 +433,8 @@ public class ExecutionVisitor extends EmptyVisitor{ } } else{ //t.getSize() is 1 - Type u = stack().pop(); - Type v = stack().pop(); + final Type u = stack().pop(); + final Type v = stack().pop(); if (v.getSize() == 2) { stack().push(u); stack().push(t); @@ -442,7 +442,7 @@ public class ExecutionVisitor extends EmptyVisitor{ stack().push(u); stack().push(t); }else{ - Type w = stack().pop(); + final Type w = stack().pop(); stack().push(u); stack().push(t); stack().push(w); @@ -837,7 +837,7 @@ public class ExecutionVisitor extends EmptyVisitor{ @Override public void visitINVOKESPECIAL(final INVOKESPECIAL o) { if (o.getMethodName(cpg).equals(Const.CONSTRUCTOR_NAME)) { - UninitializedObjectType t = (UninitializedObjectType) stack().peek(o.getArgumentTypes(cpg).length); + final UninitializedObjectType t = (UninitializedObjectType) stack().peek(o.getArgumentTypes(cpg).length); if (t == Frame.getThis()) { Frame.setThis(null); } @@ -1040,7 +1040,7 @@ public class ExecutionVisitor extends EmptyVisitor{ /** Symbolically executes the corresponding Java Virtual Machine instruction. */ @Override public void visitLDC(final LDC o) { - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (c instanceof ConstantInteger) { stack().push(Type.INT); } @@ -1056,7 +1056,7 @@ public class ExecutionVisitor extends EmptyVisitor{ } /** Symbolically executes the corresponding Java Virtual Machine instruction. */ public void visitLDC_W(final LDC_W o) { - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (c instanceof ConstantInteger) { stack().push(Type.INT); } @@ -1073,7 +1073,7 @@ public class ExecutionVisitor extends EmptyVisitor{ /** Symbolically executes the corresponding Java Virtual Machine instruction. */ @Override public void visitLDC2_W(final LDC2_W o) { - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (c instanceof ConstantLong) { stack().push(Type.LONG); } @@ -1212,7 +1212,7 @@ public class ExecutionVisitor extends EmptyVisitor{ /** Symbolically executes the corresponding Java Virtual Machine instruction. */ @Override public void visitPOP2(final POP2 o) { - Type t = stack().pop(); + final Type t = stack().pop(); if (t.getSize() == 1) { stack().pop(); } @@ -1261,8 +1261,8 @@ public class ExecutionVisitor extends EmptyVisitor{ /** Symbolically executes the corresponding Java Virtual Machine instruction. */ @Override public void visitSWAP(final SWAP o) { - Type t = stack().pop(); - Type u = stack().pop(); + final Type t = stack().pop(); + final Type u = stack().pop(); stack().push(t); stack().push(u); } diff --git a/src/main/java/org/apache/bcel/verifier/structurals/Frame.java b/src/main/java/org/apache/bcel/verifier/structurals/Frame.java index 08917bb1..2eb05543 100644 --- a/src/main/java/org/apache/bcel/verifier/structurals/Frame.java +++ b/src/main/java/org/apache/bcel/verifier/structurals/Frame.java @@ -70,7 +70,7 @@ public class Frame{ */ @Override protected Object clone() { - Frame f = new Frame(locals.getClone(), stack.getClone()); + final Frame f = new Frame(locals.getClone(), stack.getClone()); return f; } @@ -108,7 +108,7 @@ public class Frame{ if (!(o instanceof Frame)) { return false; // implies "null" is non-equal. } - Frame f = (Frame) o; + final Frame f = (Frame) o; return this.stack.equals(f.stack) && this.locals.equals(f.locals); } diff --git a/src/main/java/org/apache/bcel/verifier/structurals/InstConstraintVisitor.java b/src/main/java/org/apache/bcel/verifier/structurals/InstConstraintVisitor.java index 1c6cc79e..9aac5bb1 100644 --- a/src/main/java/org/apache/bcel/verifier/structurals/InstConstraintVisitor.java +++ b/src/main/java/org/apache/bcel/verifier/structurals/InstConstraintVisitor.java @@ -108,7 +108,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ * @throws StructuralCodeConstraintException always. */ private void constraintViolated(final Instruction violator, final String description) { - String fq_classname = violator.getClass().getName(); + final String fq_classname = violator.getClass().getName(); throw new StructuralCodeConstraintException( "Instruction "+ fq_classname.substring(fq_classname.lastIndexOf('.')+1) +" constraint violated: " + description); } @@ -204,13 +204,13 @@ public class InstConstraintVisitor extends EmptyVisitor{ * @see #visitStackInstruction(StackInstruction o) */ private void _visitStackAccessor(final Instruction o) { - int consume = o.consumeStack(cpg); // Stack values are always consumed first; then produced. + final int consume = o.consumeStack(cpg); // Stack values are always consumed first; then produced. if (consume > stack().slotsUsed()) { constraintViolated(o, "Cannot consume "+consume+" stack slots: only "+stack().slotsUsed()+" slot(s) left on stack!\nStack:\n"+stack()); } - int produce = o.produceStack(cpg) - o.consumeStack(cpg); // Stack values are always consumed first; then produced. + final int produce = o.produceStack(cpg) - o.consumeStack(cpg); // Stack values are always consumed first; then produced. if ( produce + stack().slotsUsed() > stack().maxStack() ) { constraintViolated(o, "Cannot produce "+produce+" stack slots: only "+(stack().maxStack()-stack().slotsUsed())+ " free stack slot(s) left.\nStack:\n"+stack()); @@ -229,10 +229,10 @@ public class InstConstraintVisitor extends EmptyVisitor{ */ @Override public void visitLoadClass(final LoadClass o) { - ObjectType t = o.getLoadClassType(cpg); + final ObjectType t = o.getLoadClassType(cpg); if (t != null) {// null means "no class is loaded" - Verifier v = VerifierFactory.getVerifier(t.getClassName()); - VerificationResult vr = v.doPass2(); + final Verifier v = VerifierFactory.getVerifier(t.getClassName()); + final VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK) { constraintViolated((Instruction) o, "Class '"+o.getLoadClassType(cpg).getClassName()+ "' is referenced, but cannot be loaded and resolved: '"+vr+"'."); @@ -267,7 +267,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ */ @Override public void visitCPInstruction(final CPInstruction o) { - int idx = o.getIndex(); + final int idx = o.getIndex(); if ((idx < 0) || (idx >= cpg.getSize())) { throw new AssertionViolatedException( "Huh?! Constant pool index of instruction '"+o+"' illegal? Pass 3a should have checked this!"); @@ -283,17 +283,17 @@ public class InstConstraintVisitor extends EmptyVisitor{ // implements LoadClass. // visitCPInstruction(o) has been called before. // A FieldInstruction may be: GETFIELD, GETSTATIC, PUTFIELD, PUTSTATIC - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (!(c instanceof ConstantFieldref)) { constraintViolated(o, "Index '"+o.getIndex()+"' should refer to a CONSTANT_Fieldref_info structure, but refers to '"+c+"'."); } // the o.getClassType(cpg) type has passed pass 2; see visitLoadClass(o). - Type t = o.getType(cpg); + final Type t = o.getType(cpg); if (t instanceof ObjectType) { - String name = ((ObjectType)t).getClassName(); - Verifier v = VerifierFactory.getVerifier( name ); - VerificationResult vr = v.doPass2(); + final String name = ((ObjectType)t).getClassName(); + final Verifier v = VerifierFactory.getVerifier( name ); + final VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK) { constraintViolated(o, "Class '"+name+"' is referenced, but cannot be loaded and resolved: '"+vr+"'."); } @@ -393,7 +393,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ } } else{ // we deal with ASTORE - Type stacktop = stack().peek(); + final Type stacktop = stack().peek(); if ( (!(stacktop instanceof ReferenceType)) && (!(stacktop instanceof ReturnaddressType)) ) { constraintViolated(o, "Stack top type and STOREing Instruction type mismatch: Stack top: '"+stack().peek()+ "'; Instruction expects a ReferenceType or a ReturnadressType."); @@ -461,8 +461,8 @@ public class InstConstraintVisitor extends EmptyVisitor{ */ @Override public void visitAALOAD(final AALOAD o) { - Type arrayref = stack().peek(1); - Type index = stack().peek(0); + final Type arrayref = stack().peek(1); + final Type index = stack().peek(0); indexOfInt(o, index); if (arrayrefOfArrayType(o, arrayref)) { @@ -480,9 +480,9 @@ public class InstConstraintVisitor extends EmptyVisitor{ */ @Override public void visitAASTORE(final AASTORE o) { - Type arrayref = stack().peek(2); - Type index = stack().peek(1); - Type value = stack().peek(0); + final Type arrayref = stack().peek(2); + final Type index = stack().peek(1); + final Type value = stack().peek(0); indexOfInt(o, index); if (!(value instanceof ReferenceType)) { @@ -539,7 +539,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (! (stack().peek() instanceof ReferenceType) ) { constraintViolated(o, "The 'objectref' at the stack top is not of a ReferenceType but of type '"+stack().peek()+"'."); } - ReferenceType objectref = (ReferenceType) (stack().peek()); + final ReferenceType objectref = (ReferenceType) (stack().peek()); referenceTypeIsInitialized(o, objectref); // The check below should already done via visitReturnInstruction(ReturnInstruction), see there. @@ -556,7 +556,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ */ @Override public void visitARRAYLENGTH(final ARRAYLENGTH o) { - Type arrayref = stack().peek(0); + final Type arrayref = stack().peek(0); arrayrefOfArrayType(o, arrayref); } @@ -590,13 +590,13 @@ public class InstConstraintVisitor extends EmptyVisitor{ return; } - ObjectType exc = (ObjectType) (stack().peek()); - ObjectType throwable = (ObjectType) (Type.getType("Ljava/lang/Throwable;")); + final ObjectType exc = (ObjectType) (stack().peek()); + final ObjectType throwable = (ObjectType) (Type.getType("Ljava/lang/Throwable;")); if ( (! (exc.subclassOf(throwable)) ) && (! (exc.equals(throwable))) ) { constraintViolated(o, "The 'objectref' is not of class Throwable or of a subclass of Throwable, but of '"+stack().peek()+"'."); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -607,8 +607,8 @@ public class InstConstraintVisitor extends EmptyVisitor{ */ @Override public void visitBALOAD(final BALOAD o) { - Type arrayref = stack().peek(1); - Type index = stack().peek(0); + final Type arrayref = stack().peek(1); + final Type index = stack().peek(0); indexOfInt(o, index); if (arrayrefOfArrayType(o, arrayref)) { if (! ( (((ArrayType) arrayref).getElementType().equals(Type.BOOLEAN)) || @@ -625,9 +625,9 @@ public class InstConstraintVisitor extends EmptyVisitor{ */ @Override public void visitBASTORE(final BASTORE o) { - Type arrayref = stack().peek(2); - Type index = stack().peek(1); - Type value = stack().peek(0); + final Type arrayref = stack().peek(2); + final Type index = stack().peek(1); + final Type value = stack().peek(0); indexOfInt(o, index); valueOfInt(o, value); @@ -663,8 +663,8 @@ public class InstConstraintVisitor extends EmptyVisitor{ */ @Override public void visitCALOAD(final CALOAD o) { - Type arrayref = stack().peek(1); - Type index = stack().peek(0); + final Type arrayref = stack().peek(1); + final Type index = stack().peek(0); indexOfInt(o, index); arrayrefOfArrayType(o, arrayref); @@ -675,9 +675,9 @@ public class InstConstraintVisitor extends EmptyVisitor{ */ @Override public void visitCASTORE(final CASTORE o) { - Type arrayref = stack().peek(2); - Type index = stack().peek(1); - Type value = stack().peek(0); + final Type arrayref = stack().peek(2); + final Type index = stack().peek(1); + final Type value = stack().peek(0); indexOfInt(o, index); valueOfInt(o, value); @@ -695,7 +695,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ @Override public void visitCHECKCAST(final CHECKCAST o) { // The objectref must be of type reference. - Type objectref = stack().peek(0); + final Type objectref = stack().peek(0); if (!(objectref instanceof ReferenceType)) { constraintViolated(o, "The 'objectref' is not of a ReferenceType but of type "+objectref+"."); } @@ -705,7 +705,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ // The unsigned indexbyte1 and indexbyte2 are used to construct an index into the runtime constant pool of the // current class (�3.6), where the value of the index is (indexbyte1 << 8) | indexbyte2. The runtime constant // pool item at the index must be a symbolic reference to a class, array, or interface type. - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)) { constraintViolated(o, "The Constant at 'index' is not a ConstantClass, but '"+c+"'."); } @@ -766,7 +766,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (! (stack().peek(1) instanceof ArrayType)) { constraintViolated(o, "Stack next-to-top must be of type double[] but is '"+stack().peek(1)+"'."); } - Type t = ((ArrayType) (stack().peek(1))).getBasicType(); + final Type t = ((ArrayType) (stack().peek(1))).getBasicType(); if (t != Type.DOUBLE) { constraintViolated(o, "Stack next-to-top must be of type double[] but is '"+stack().peek(1)+"'."); } @@ -787,7 +787,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (! (stack().peek(2) instanceof ArrayType)) { constraintViolated(o, "Stack next-to-next-to-top must be of type double[] but is '"+stack().peek(2)+"'."); } - Type t = ((ArrayType) (stack().peek(2))).getBasicType(); + final Type t = ((ArrayType) (stack().peek(2))).getBasicType(); if (t != Type.DOUBLE) { constraintViolated(o, "Stack next-to-next-to-top must be of type double[] but is '"+stack().peek(2)+"'."); } @@ -1097,7 +1097,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (! (stack().peek(1) instanceof ArrayType)) { constraintViolated(o, "Stack next-to-top must be of type float[] but is '"+stack().peek(1)+"'."); } - Type t = ((ArrayType) (stack().peek(1))).getBasicType(); + final Type t = ((ArrayType) (stack().peek(1))).getBasicType(); if (t != Type.FLOAT) { constraintViolated(o, "Stack next-to-top must be of type float[] but is '"+stack().peek(1)+"'."); } @@ -1118,7 +1118,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (! (stack().peek(2) instanceof ArrayType)) { constraintViolated(o, "Stack next-to-next-to-top must be of type float[] but is '"+stack().peek(2)+"'."); } - Type t = ((ArrayType) (stack().peek(2))).getBasicType(); + final Type t = ((ArrayType) (stack().peek(2))).getBasicType(); if (t != Type.FLOAT) { constraintViolated(o, "Stack next-to-next-to-top must be of type float[] but is '"+stack().peek(2)+"'."); } @@ -1251,7 +1251,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ } private ObjectType getObjectType(final FieldInstruction o) { - ReferenceType rt = o.getReferenceType(cpg); + final ReferenceType rt = o.getReferenceType(cpg); if(rt instanceof ObjectType) { return (ObjectType)rt; } @@ -1265,20 +1265,20 @@ public class InstConstraintVisitor extends EmptyVisitor{ @Override public void visitGETFIELD(final GETFIELD o) { try { - Type objectref = stack().peek(); + final Type objectref = stack().peek(); if (! ( (objectref instanceof ObjectType) || (objectref == Type.NULL) ) ) { constraintViolated(o, "Stack top should be an object reference that's not an array reference, but is '"+objectref+"'."); } - String field_name = o.getFieldName(cpg); + final String field_name = o.getFieldName(cpg); - JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); + final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); Field[] fields = jc.getFields(); Field f = null; - for (Field field : fields) { + for (final Field field : fields) { if (field.getName().equals(field_name)) { - Type f_type = Type.getType(field.getSignature()); - Type o_type = o.getType(cpg); + final Type f_type = Type.getType(field.getSignature()); + final Type o_type = o.getType(cpg); /* TODO: Check if assignment compatibility is sufficient. * What does Sun do? */ @@ -1290,14 +1290,14 @@ public class InstConstraintVisitor extends EmptyVisitor{ } if (f == null) { - JavaClass[] superclasses = jc.getSuperClasses(); + final JavaClass[] superclasses = jc.getSuperClasses(); outer: - for (JavaClass superclass : superclasses) { + for (final JavaClass superclass : superclasses) { fields = superclass.getFields(); - for (Field field : fields) { + for (final Field field : fields) { if (field.getName().equals(field_name)) { - Type f_type = Type.getType(field.getSignature()); - Type o_type = o.getType(cpg); + final Type f_type = Type.getType(field.getSignature()); + final Type o_type = o.getType(cpg); if (f_type.equals(o_type)) { f = field; if ((f.getAccessFlags() & (Const.ACC_PUBLIC | Const.ACC_PROTECTED)) == 0) { @@ -1314,19 +1314,19 @@ public class InstConstraintVisitor extends EmptyVisitor{ } if (f.isProtected()) { - ObjectType classtype = getObjectType(o); - ObjectType curr = ObjectType.getInstance(mg.getClassName()); + final ObjectType classtype = getObjectType(o); + final ObjectType curr = ObjectType.getInstance(mg.getClassName()); if ( classtype.equals(curr) || curr.subclassOf(classtype) ) { - Type t = stack().peek(); + final Type t = stack().peek(); if (t == Type.NULL) { return; } if (! (t instanceof ObjectType) ) { constraintViolated(o, "The 'objectref' must refer to an object that's not an array. Found instead: '"+t+"'."); } - ObjectType objreftype = (ObjectType) t; + final ObjectType objreftype = (ObjectType) t; if (! ( objreftype.equals(curr) || objreftype.subclassOf(curr) ) ) { //TODO: One day move to Staerk-et-al's "Set of object types" instead of "wider" object types @@ -1345,7 +1345,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ constraintViolated(o, "Referenced field '"+f+"' is static which it shouldn't be."); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -1460,7 +1460,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (! (stack().peek(1) instanceof ArrayType)) { constraintViolated(o, "Stack next-to-top must be of type int[] but is '"+stack().peek(1)+"'."); } - Type t = ((ArrayType) (stack().peek(1))).getBasicType(); + final Type t = ((ArrayType) (stack().peek(1))).getBasicType(); if (t != Type.INT) { constraintViolated(o, "Stack next-to-top must be of type int[] but is '"+stack().peek(1)+"'."); } @@ -1494,7 +1494,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (! (stack().peek(2) instanceof ArrayType)) { constraintViolated(o, "Stack next-to-next-to-top must be of type int[] but is '"+stack().peek(2)+"'."); } - Type t = ((ArrayType) (stack().peek(2))).getBasicType(); + final Type t = ((ArrayType) (stack().peek(2))).getBasicType(); if (t != Type.INT) { constraintViolated(o, "Stack next-to-next-to-top must be of type int[] but is '"+stack().peek(2)+"'."); } @@ -1781,7 +1781,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ @Override public void visitINSTANCEOF(final INSTANCEOF o) { // The objectref must be of type reference. - Type objectref = stack().peek(0); + final Type objectref = stack().peek(0); if (!(objectref instanceof ReferenceType)) { constraintViolated(o, "The 'objectref' is not of a ReferenceType but of type "+objectref+"."); } @@ -1791,7 +1791,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ // The unsigned indexbyte1 and indexbyte2 are used to construct an index into the runtime constant pool of the // current class (�3.6), where the value of the index is (indexbyte1 << 8) | indexbyte2. The runtime constant // pool item at the index must be a symbolic reference to a class, array, or interface type. - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! (c instanceof ConstantClass)) { constraintViolated(o, "The Constant at 'index' is not a ConstantClass, but '"+c+"'."); } @@ -1813,7 +1813,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ public void visitINVOKEINTERFACE(final INVOKEINTERFACE o) { // Method is not native, otherwise pass 3 would not happen. - int count = o.getCount(); + final int count = o.getCount(); if (count == 0) { constraintViolated(o, "The 'count' argument must not be 0."); } @@ -1823,22 +1823,22 @@ public class InstConstraintVisitor extends EmptyVisitor{ // the o.getClassType(cpg) type has passed pass 2; see visitLoadClass(o). - Type t = o.getType(cpg); + final Type t = o.getType(cpg); if (t instanceof ObjectType) { - String name = ((ObjectType)t).getClassName(); - Verifier v = VerifierFactory.getVerifier( name ); - VerificationResult vr = v.doPass2(); + final String name = ((ObjectType)t).getClassName(); + final Verifier v = VerifierFactory.getVerifier( name ); + final VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK) { constraintViolated(o, "Class '"+name+"' is referenced, but cannot be loaded and resolved: '"+vr+"'."); } } - Type[] argtypes = o.getArgumentTypes(cpg); - int nargs = argtypes.length; + final Type[] argtypes = o.getArgumentTypes(cpg); + final int nargs = argtypes.length; for (int i=nargs-1; i>=0; i--) { - Type fromStack = stack().peek( (nargs-1) - i ); // 0 to nargs-1 + final Type fromStack = stack().peek( (nargs-1) - i ); // 0 to nargs-1 Type fromDesc = argtypes[i]; if (fromDesc == Type.BOOLEAN || fromDesc == Type.BYTE || @@ -1848,7 +1848,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ } if (! fromStack.equals(fromDesc)) { if (fromStack instanceof ReferenceType && fromDesc instanceof ReferenceType) { - ReferenceType rFromStack = (ReferenceType) fromStack; + final ReferenceType rFromStack = (ReferenceType) fromStack; //ReferenceType rFromDesc = (ReferenceType) fromDesc; // TODO: This can only be checked when using Staerk-et-al's "set of object types" // instead of a "wider cast object type" created during verification. @@ -1915,22 +1915,22 @@ public class InstConstraintVisitor extends EmptyVisitor{ // the o.getClassType(cpg) type has passed pass 2; see visitLoadClass(o). - Type t = o.getType(cpg); + final Type t = o.getType(cpg); if (t instanceof ObjectType) { - String name = ((ObjectType)t).getClassName(); - Verifier v = VerifierFactory.getVerifier( name ); - VerificationResult vr = v.doPass2(); + final String name = ((ObjectType)t).getClassName(); + final Verifier v = VerifierFactory.getVerifier( name ); + final VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK) { constraintViolated(o, "Class '"+name+"' is referenced, but cannot be loaded and resolved: '"+vr+"'."); } } - Type[] argtypes = o.getArgumentTypes(cpg); - int nargs = argtypes.length; + final Type[] argtypes = o.getArgumentTypes(cpg); + final int nargs = argtypes.length; for (int i=nargs-1; i>=0; i--) { - Type fromStack = stack().peek( (nargs-1) - i ); // 0 to nargs-1 + final Type fromStack = stack().peek( (nargs-1) - i ); // 0 to nargs-1 Type fromDesc = argtypes[i]; if (fromDesc == Type.BOOLEAN || fromDesc == Type.BYTE || @@ -1940,8 +1940,8 @@ public class InstConstraintVisitor extends EmptyVisitor{ } if (! fromStack.equals(fromDesc)) { if (fromStack instanceof ReferenceType && fromDesc instanceof ReferenceType) { - ReferenceType rFromStack = (ReferenceType) fromStack; - ReferenceType rFromDesc = (ReferenceType) fromDesc; + final ReferenceType rFromStack = (ReferenceType) fromStack; + final ReferenceType rFromDesc = (ReferenceType) fromDesc; // TODO: This can only be checked using Staerk-et-al's "set of object types", not // using a "wider cast object type". if ( ! rFromStack.isAssignmentCompatibleWith(rFromDesc) ) { @@ -1986,12 +1986,12 @@ public class InstConstraintVisitor extends EmptyVisitor{ } - String theClass = o.getClassName(cpg); + final String theClass = o.getClassName(cpg); if ( ! Repository.instanceOf(objref_classname, theClass) ) { constraintViolated(o, "The 'objref' item '"+objref+"' does not implement '"+theClass+"' as expected."); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -2005,21 +2005,21 @@ public class InstConstraintVisitor extends EmptyVisitor{ try { // Method is not native, otherwise pass 3 would not happen. - Type t = o.getType(cpg); + final Type t = o.getType(cpg); if (t instanceof ObjectType) { - String name = ((ObjectType)t).getClassName(); - Verifier v = VerifierFactory.getVerifier( name ); - VerificationResult vr = v.doPass2(); + final String name = ((ObjectType)t).getClassName(); + final Verifier v = VerifierFactory.getVerifier( name ); + final VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK) { constraintViolated(o, "Class '"+name+"' is referenced, but cannot be loaded and resolved: '"+vr+"'."); } } - Type[] argtypes = o.getArgumentTypes(cpg); - int nargs = argtypes.length; + final Type[] argtypes = o.getArgumentTypes(cpg); + final int nargs = argtypes.length; for (int i=nargs-1; i>=0; i--) { - Type fromStack = stack().peek( (nargs-1) - i ); // 0 to nargs-1 + final Type fromStack = stack().peek( (nargs-1) - i ); // 0 to nargs-1 Type fromDesc = argtypes[i]; if (fromDesc == Type.BOOLEAN || fromDesc == Type.BYTE || @@ -2029,8 +2029,8 @@ public class InstConstraintVisitor extends EmptyVisitor{ } if (! fromStack.equals(fromDesc)) { if (fromStack instanceof ReferenceType && fromDesc instanceof ReferenceType) { - ReferenceType rFromStack = (ReferenceType) fromStack; - ReferenceType rFromDesc = (ReferenceType) fromDesc; + final ReferenceType rFromStack = (ReferenceType) fromStack; + final ReferenceType rFromDesc = (ReferenceType) fromDesc; // TODO: This check can possibly only be done using Staerk-et-al's "set of object types" // instead of a "wider cast object type" created during verification. if ( ! rFromStack.isAssignmentCompatibleWith(rFromDesc) ) { @@ -2044,7 +2044,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ } } } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -2058,22 +2058,22 @@ public class InstConstraintVisitor extends EmptyVisitor{ try { // the o.getClassType(cpg) type has passed pass 2; see visitLoadClass(o). - Type t = o.getType(cpg); + final Type t = o.getType(cpg); if (t instanceof ObjectType) { - String name = ((ObjectType)t).getClassName(); - Verifier v = VerifierFactory.getVerifier( name ); - VerificationResult vr = v.doPass2(); + final String name = ((ObjectType)t).getClassName(); + final Verifier v = VerifierFactory.getVerifier( name ); + final VerificationResult vr = v.doPass2(); if (vr.getStatus() != VerificationResult.VERIFIED_OK) { constraintViolated(o, "Class '"+name+"' is referenced, but cannot be loaded and resolved: '"+vr+"'."); } } - Type[] argtypes = o.getArgumentTypes(cpg); - int nargs = argtypes.length; + final Type[] argtypes = o.getArgumentTypes(cpg); + final int nargs = argtypes.length; for (int i=nargs-1; i>=0; i--) { - Type fromStack = stack().peek( (nargs-1) - i ); // 0 to nargs-1 + final Type fromStack = stack().peek( (nargs-1) - i ); // 0 to nargs-1 Type fromDesc = argtypes[i]; if (fromDesc == Type.BOOLEAN || fromDesc == Type.BYTE || @@ -2083,8 +2083,8 @@ public class InstConstraintVisitor extends EmptyVisitor{ } if (! fromStack.equals(fromDesc)) { if (fromStack instanceof ReferenceType && fromDesc instanceof ReferenceType) { - ReferenceType rFromStack = (ReferenceType) fromStack; - ReferenceType rFromDesc = (ReferenceType) fromDesc; + final ReferenceType rFromStack = (ReferenceType) fromStack; + final ReferenceType rFromDesc = (ReferenceType) fromDesc; // TODO: This can possibly only be checked when using Staerk-et-al's "set of object types" instead // of a single "wider cast object type" created during verification. if ( ! rFromStack.isAssignmentCompatibleWith(rFromDesc) ) { @@ -2116,14 +2116,14 @@ public class InstConstraintVisitor extends EmptyVisitor{ } } - String objref_classname = ((ObjectType) objref).getClassName(); + final String objref_classname = ((ObjectType) objref).getClassName(); - String theClass = o.getClassName(cpg); + final String theClass = o.getClassName(cpg); if ( ! Repository.instanceOf(objref_classname, theClass) ) { constraintViolated(o, "The 'objref' item '"+objref+"' does not implement '"+theClass+"' as expected."); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -2311,7 +2311,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (! (stack().peek(1) instanceof ArrayType)) { constraintViolated(o, "Stack next-to-top must be of type long[] but is '"+stack().peek(1)+"'."); } - Type t = ((ArrayType) (stack().peek(1))).getBasicType(); + final Type t = ((ArrayType) (stack().peek(1))).getBasicType(); if (t != Type.LONG) { constraintViolated(o, "Stack next-to-top must be of type long[] but is '"+stack().peek(1)+"'."); } @@ -2345,7 +2345,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (! (stack().peek(2) instanceof ArrayType)) { constraintViolated(o, "Stack next-to-next-to-top must be of type long[] but is '"+stack().peek(2)+"'."); } - Type t = ((ArrayType) (stack().peek(2))).getBasicType(); + final Type t = ((ArrayType) (stack().peek(2))).getBasicType(); if (t != Type.LONG) { constraintViolated(o, "Stack next-to-next-to-top must be of type long[] but is '"+stack().peek(2)+"'."); } @@ -2379,7 +2379,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ public void visitLDC(final LDC o) { // visitCPInstruction is called first. - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! ( ( c instanceof ConstantInteger) || ( c instanceof ConstantFloat ) || ( c instanceof ConstantString ) || @@ -2396,7 +2396,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ public void visitLDC_W(final LDC_W o) { // visitCPInstruction is called first. - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! ( ( c instanceof ConstantInteger) || ( c instanceof ConstantFloat ) || ( c instanceof ConstantString ) || @@ -2414,7 +2414,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ public void visitLDC2_W(final LDC2_W o) { // visitCPInstruction is called first. - Constant c = cpg.getConstant(o.getIndex()); + final Constant c = cpg.getConstant(o.getIndex()); if (! ( ( c instanceof ConstantLong) || ( c instanceof ConstantDouble ) ) ) { constraintViolated(o, @@ -2617,7 +2617,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ */ @Override public void visitMULTIANEWARRAY(final MULTIANEWARRAY o) { - int dimensions = o.getDimensions(); + final int dimensions = o.getDimensions(); // Dimensions argument is okay: see Pass 3a. for (int i=0; i<dimensions; i++) { if (stack().peek(i) != Type.INT) { @@ -2636,21 +2636,21 @@ public class InstConstraintVisitor extends EmptyVisitor{ //visitCPInstruction(CPInstruction) has been called before. //visitLoadClass(LoadClass) has been called before. - Type t = o.getType(cpg); + final Type t = o.getType(cpg); if (! (t instanceof ReferenceType)) { throw new AssertionViolatedException("NEW.getType() returning a non-reference type?!"); } if (! (t instanceof ObjectType)) { constraintViolated(o, "Expecting a class type (ObjectType) to work on. Found: '"+t+"'."); } - ObjectType obj = (ObjectType) t; + final ObjectType obj = (ObjectType) t; //e.g.: Don't instantiate interfaces try { if (! obj.referencesClassExact()) { constraintViolated(o, "Expecting a class type (ObjectType) to work on. Found: '"+obj+"'."); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { constraintViolated(o, "Expecting a class type (ObjectType) to work on. Found: '"+obj+"'." + " which threw " + e); } } @@ -2702,21 +2702,21 @@ public class InstConstraintVisitor extends EmptyVisitor{ public void visitPUTFIELD(final PUTFIELD o) { try { - Type objectref = stack().peek(1); + final Type objectref = stack().peek(1); if (! ( (objectref instanceof ObjectType) || (objectref == Type.NULL) ) ) { constraintViolated(o, "Stack next-to-top should be an object reference that's not an array reference, but is '"+objectref+"'."); } - String field_name = o.getFieldName(cpg); + final String field_name = o.getFieldName(cpg); - JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); - Field[] fields = jc.getFields(); + final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); + final Field[] fields = jc.getFields(); Field f = null; - for (Field field : fields) { + for (final Field field : fields) { if (field.getName().equals(field_name)) { - Type f_type = Type.getType(field.getSignature()); - Type o_type = o.getType(cpg); + final Type f_type = Type.getType(field.getSignature()); + final Type o_type = o.getType(cpg); /* TODO: Check if assignment compatibility is sufficient. * What does Sun do? */ @@ -2730,8 +2730,8 @@ public class InstConstraintVisitor extends EmptyVisitor{ throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName()); } - Type value = stack().peek(); - Type t = Type.getType(f.getSignature()); + final Type value = stack().peek(); + final Type t = Type.getType(f.getSignature()); Type shouldbe = t; if (shouldbe == Type.BOOLEAN || shouldbe == Type.BYTE || @@ -2762,19 +2762,19 @@ public class InstConstraintVisitor extends EmptyVisitor{ } if (f.isProtected()) { - ObjectType classtype = getObjectType(o); - ObjectType curr = ObjectType.getInstance(mg.getClassName()); + final ObjectType classtype = getObjectType(o); + final ObjectType curr = ObjectType.getInstance(mg.getClassName()); if ( classtype.equals(curr) || curr.subclassOf(classtype) ) { - Type tp = stack().peek(1); + final Type tp = stack().peek(1); if (tp == Type.NULL) { return; } if (! (tp instanceof ObjectType) ) { constraintViolated(o, "The 'objectref' must refer to an object that's not an array. Found instead: '"+tp+"'."); } - ObjectType objreftype = (ObjectType) tp; + final ObjectType objreftype = (ObjectType) tp; if (! ( objreftype.equals(curr) || objreftype.subclassOf(curr) ) ) { constraintViolated(o, @@ -2790,7 +2790,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ constraintViolated(o, "Referenced field '"+f+"' is static which it shouldn't be."); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -2802,14 +2802,14 @@ public class InstConstraintVisitor extends EmptyVisitor{ @Override public void visitPUTSTATIC(final PUTSTATIC o) { try { - String field_name = o.getFieldName(cpg); - JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); - Field[] fields = jc.getFields(); + final String field_name = o.getFieldName(cpg); + final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName()); + final Field[] fields = jc.getFields(); Field f = null; - for (Field field : fields) { + for (final Field field : fields) { if (field.getName().equals(field_name)) { - Type f_type = Type.getType(field.getSignature()); - Type o_type = o.getType(cpg); + final Type f_type = Type.getType(field.getSignature()); + final Type o_type = o.getType(cpg); /* TODO: Check if assignment compatibility is sufficient. * What does Sun do? */ @@ -2822,8 +2822,8 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (f == null) { throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName()); } - Type value = stack().peek(); - Type t = Type.getType(f.getSignature()); + final Type value = stack().peek(); + final Type t = Type.getType(f.getSignature()); Type shouldbe = t; if (shouldbe == Type.BOOLEAN || shouldbe == Type.BYTE || @@ -2855,7 +2855,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ // TODO: Interface fields may be assigned to only once. (Hard to implement in // JustIce's execution model). This may only happen in <clinit>, see Pass 3a. - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -2900,7 +2900,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (! (stack().peek(1) instanceof ArrayType)) { constraintViolated(o, "Stack next-to-top must be of type short[] but is '"+stack().peek(1)+"'."); } - Type t = ((ArrayType) (stack().peek(1))).getBasicType(); + final Type t = ((ArrayType) (stack().peek(1))).getBasicType(); if (t != Type.SHORT) { constraintViolated(o, "Stack next-to-top must be of type short[] but is '"+stack().peek(1)+"'."); } @@ -2921,7 +2921,7 @@ public class InstConstraintVisitor extends EmptyVisitor{ if (! (stack().peek(2) instanceof ArrayType)) { constraintViolated(o, "Stack next-to-next-to-top must be of type short[] but is '"+stack().peek(2)+"'."); } - Type t = ((ArrayType) (stack().peek(2))).getBasicType(); + final Type t = ((ArrayType) (stack().peek(2))).getBasicType(); if (t != Type.SHORT) { constraintViolated(o, "Stack next-to-next-to-top must be of type short[] but is '"+stack().peek(2)+"'."); } diff --git a/src/main/java/org/apache/bcel/verifier/structurals/LocalVariables.java b/src/main/java/org/apache/bcel/verifier/structurals/LocalVariables.java index 95c562a2..71c3f76b 100644 --- a/src/main/java/org/apache/bcel/verifier/structurals/LocalVariables.java +++ b/src/main/java/org/apache/bcel/verifier/structurals/LocalVariables.java @@ -50,7 +50,7 @@ public class LocalVariables implements Cloneable { */ @Override public Object clone() { - LocalVariables lvs = new LocalVariables(locals.length); + final LocalVariables lvs = new LocalVariables(locals.length); for (int i=0; i<locals.length; i++) { lvs.locals[i] = this.locals[i]; } @@ -103,7 +103,7 @@ public class LocalVariables implements Cloneable { if (!(o instanceof LocalVariables)) { return false; } - LocalVariables lv = (LocalVariables) o; + final LocalVariables lv = (LocalVariables) o; if (this.locals.length != lv.locals.length) { return false; } @@ -159,7 +159,7 @@ public class LocalVariables implements Cloneable { } if ((locals[i] instanceof ReferenceType) && (lv.locals[i] instanceof ReferenceType)) { if (! locals[i].equals(lv.locals[i])) { // needed in case of two UninitializedObjectType instances - Type sup = ((ReferenceType) locals[i]).getFirstCommonSuperclass((ReferenceType) (lv.locals[i])); + final Type sup = ((ReferenceType) locals[i]).getFirstCommonSuperclass((ReferenceType) (lv.locals[i])); if (sup != null) { locals[i] = sup; @@ -183,7 +183,7 @@ public class LocalVariables implements Cloneable { locals[i] = Type.UNKNOWN; } } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } @@ -194,7 +194,7 @@ public class LocalVariables implements Cloneable { */ @Override public String toString() { - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); for (int i=0; i<locals.length; i++) { sb.append(Integer.toString(i)); sb.append(": "); diff --git a/src/main/java/org/apache/bcel/verifier/structurals/OperandStack.java b/src/main/java/org/apache/bcel/verifier/structurals/OperandStack.java index 8f894107..3eb306f1 100644 --- a/src/main/java/org/apache/bcel/verifier/structurals/OperandStack.java +++ b/src/main/java/org/apache/bcel/verifier/structurals/OperandStack.java @@ -63,7 +63,7 @@ public class OperandStack implements Cloneable { */ @Override public Object clone() { - OperandStack newstack = new OperandStack(this.maxStack); + final OperandStack newstack = new OperandStack(this.maxStack); @SuppressWarnings("unchecked") // OK because this.stack is the same type final ArrayList<Type> clone = (ArrayList<Type>) this.stack.clone(); newstack.stack = clone; @@ -92,7 +92,7 @@ public class OperandStack implements Cloneable { if (!(o instanceof OperandStack)) { return false; } - OperandStack s = (OperandStack) o; + final OperandStack s = (OperandStack) o; return this.stack.equals(s.stack); } @@ -138,7 +138,7 @@ public class OperandStack implements Cloneable { * Returns the element on top of the stack. The element is popped off the stack. */ public Type pop() { - Type e = stack.remove(size()-1); + final Type e = stack.remove(size()-1); return e; } @@ -197,7 +197,7 @@ public class OperandStack implements Cloneable { */ @Override public String toString() { - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); sb.append("Slots used: "); sb.append(slotsUsed()); sb.append(" MaxStack: "); @@ -253,7 +253,7 @@ public class OperandStack implements Cloneable { } } } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } diff --git a/src/main/java/org/apache/bcel/verifier/structurals/Pass3bVerifier.java b/src/main/java/org/apache/bcel/verifier/structurals/Pass3bVerifier.java index 1790e7c8..9c855a3b 100644 --- a/src/main/java/org/apache/bcel/verifier/structurals/Pass3bVerifier.java +++ b/src/main/java/org/apache/bcel/verifier/structurals/Pass3bVerifier.java @@ -129,7 +129,7 @@ public final class Pass3bVerifier extends PassVerifier{ private void circulationPump(final MethodGen m,final ControlFlowGraph cfg, final InstructionContext start, final Frame vanillaFrame, final InstConstraintVisitor icv, final ExecutionVisitor ev) { final Random random = new Random(); - InstructionContextQueue icq = new InstructionContextQueue(); + final InstructionContextQueue icq = new InstructionContextQueue(); start.execute(vanillaFrame, new ArrayList<InstructionContext>(), icv, ev); // new ArrayList() <=> no Instruction was executed before @@ -141,7 +141,7 @@ public final class Pass3bVerifier extends PassVerifier{ InstructionContext u; ArrayList<InstructionContext> ec; if (!DEBUG) { - int r = random.nextInt(icq.size()); + final int r = random.nextInt(icq.size()); u = icq.getIC(r); ec = icq.getEC(r); icq.remove(r); @@ -153,8 +153,10 @@ public final class Pass3bVerifier extends PassVerifier{ } @SuppressWarnings("unchecked") // ec is of type ArrayList<InstructionContext> + final ArrayList<InstructionContext> oldchain = (ArrayList<InstructionContext>) (ec.clone()); @SuppressWarnings("unchecked") // ec is of type ArrayList<InstructionContext> + final ArrayList<InstructionContext> newchain = (ArrayList<InstructionContext>) (ec.clone()); newchain.add(u); @@ -162,9 +164,9 @@ public final class Pass3bVerifier extends PassVerifier{ //System.err.println(u); // We can only follow _one_ successor, the one after the // JSR that was recently executed. - RET ret = (RET) (u.getInstruction().getInstruction()); - ReturnaddressType t = (ReturnaddressType) u.getOutFrame(oldchain).getLocals().get(ret.getIndex()); - InstructionContext theSuccessor = cfg.contextOf(t.getTarget()); + final RET ret = (RET) (u.getInstruction().getInstruction()); + final ReturnaddressType t = (ReturnaddressType) u.getOutFrame(oldchain).getLocals().get(ret.getIndex()); + final InstructionContext theSuccessor = cfg.contextOf(t.getTarget()); // Sanity check InstructionContext lastJSR = null; @@ -188,7 +190,7 @@ public final class Pass3bVerifier extends PassVerifier{ if (lastJSR == null) { throw new AssertionViolatedException("RET without a JSR before in ExecutionChain?! EC: '"+oldchain+"'."); } - JsrInstruction jsr = (JsrInstruction) (lastJSR.getInstruction().getInstruction()); + final JsrInstruction jsr = (JsrInstruction) (lastJSR.getInstruction().getInstruction()); if ( theSuccessor != (cfg.contextOf(jsr.physicalSuccessor())) ) { throw new AssertionViolatedException("RET '"+u.getInstruction()+"' info inconsistent: jump back to '"+ theSuccessor+"' or '"+cfg.contextOf(jsr.physicalSuccessor())+"'?"); @@ -196,6 +198,7 @@ public final class Pass3bVerifier extends PassVerifier{ if (theSuccessor.execute(u.getOutFrame(oldchain), newchain, icv, ev)) { @SuppressWarnings("unchecked") // newchain is already of type ArrayList<InstructionContext> + final ArrayList<InstructionContext> newchainClone = (ArrayList<InstructionContext>) newchain.clone(); icq.add(theSuccessor, newchainClone); } @@ -203,10 +206,11 @@ public final class Pass3bVerifier extends PassVerifier{ else{// "not a ret" // Normal successors. Add them to the queue of successors. - InstructionContext[] succs = u.getSuccessors(); - for (InstructionContext v : succs) { + final InstructionContext[] succs = u.getSuccessors(); + for (final InstructionContext v : succs) { if (v.execute(u.getOutFrame(oldchain), newchain, icv, ev)) { @SuppressWarnings("unchecked") // newchain is already of type ArrayList<InstructionContext> + final ArrayList<InstructionContext> newchainClone = (ArrayList<InstructionContext>) newchain.clone(); icq.add(v, newchainClone); } @@ -215,9 +219,9 @@ public final class Pass3bVerifier extends PassVerifier{ // Exception Handlers. Add them to the queue of successors. // [subroutines are never protected; mandated by JustIce] - ExceptionHandler[] exc_hds = u.getExceptionHandlers(); - for (ExceptionHandler exc_hd : exc_hds) { - InstructionContext v = cfg.contextOf(exc_hd.getHandlerStart()); + final ExceptionHandler[] exc_hds = u.getExceptionHandlers(); + for (final ExceptionHandler exc_hd : exc_hds) { + final InstructionContext v = cfg.contextOf(exc_hd.getHandlerStart()); // TODO: the "oldchain" and "newchain" is used to determine the subroutine // we're in (by searching for the last JSR) by the InstructionContext // implementation. Therefore, we should not use this chain mechanism @@ -243,18 +247,18 @@ public final class Pass3bVerifier extends PassVerifier{ InstructionHandle ih = start.getInstruction(); do{ if ((ih.getInstruction() instanceof ReturnInstruction) && (!(cfg.isDead(ih)))) { - InstructionContext ic = cfg.contextOf(ih); + final InstructionContext ic = cfg.contextOf(ih); // TODO: This is buggy, we check only the top-level return instructions this way. // Maybe some maniac returns from a method when in a subroutine? - Frame f = ic.getOutFrame(new ArrayList<InstructionContext>()); - LocalVariables lvs = f.getLocals(); + final Frame f = ic.getOutFrame(new ArrayList<InstructionContext>()); + final LocalVariables lvs = f.getLocals(); for (int i=0; i<lvs.maxLocals(); i++) { if (lvs.get(i) instanceof UninitializedObjectType) { this.addMessage("Warning: ReturnInstruction '"+ic+ "' may leave method with an uninitialized object in the local variables array '"+lvs+"'."); } } - OperandStack os = f.getStack(); + final OperandStack os = f.getStack(); for (int i=0; i<os.size(); i++) { if (os.peek(i) instanceof UninitializedObjectType) { this.addMessage("Warning: ReturnInstruction '"+ic+ @@ -263,7 +267,7 @@ public final class Pass3bVerifier extends PassVerifier{ } //see JVM $4.8.2 Type returnedType = null; - OperandStack inStack = ic.getInFrame().getStack(); + final OperandStack inStack = ic.getInFrame().getStack(); if (inStack.size() >= 1) { returnedType = inStack.peek(); } else { @@ -276,7 +280,7 @@ public final class Pass3bVerifier extends PassVerifier{ if (!((ReferenceType) returnedType).isCastableTo(m.getReturnType())) { invalidReturnTypeError(returnedType, m); } - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // Don't know what do do now, so raise RuntimeException throw new RuntimeException(e); } @@ -320,34 +324,34 @@ public final class Pass3bVerifier extends PassVerifier{ JavaClass jc; try { jc = Repository.lookupClass(myOwner.getClassName()); - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { // FIXME: maybe not the best way to handle this throw new AssertionViolatedException("Missing class: " + e, e); } - ConstantPoolGen constantPoolGen = new ConstantPoolGen(jc.getConstantPool()); + final ConstantPoolGen constantPoolGen = new ConstantPoolGen(jc.getConstantPool()); // Init Visitors - InstConstraintVisitor icv = new InstConstraintVisitor(); + final InstConstraintVisitor icv = new InstConstraintVisitor(); icv.setConstantPoolGen(constantPoolGen); - ExecutionVisitor ev = new ExecutionVisitor(); + final ExecutionVisitor ev = new ExecutionVisitor(); ev.setConstantPoolGen(constantPoolGen); - Method[] methods = jc.getMethods(); // Method no "method_no" exists, we ran Pass3a before on it! + final Method[] methods = jc.getMethods(); // Method no "method_no" exists, we ran Pass3a before on it! try{ - MethodGen mg = new MethodGen(methods[method_no], myOwner.getClassName(), constantPoolGen); + final MethodGen mg = new MethodGen(methods[method_no], myOwner.getClassName(), constantPoolGen); icv.setMethodGen(mg); ////////////// DFA BEGINS HERE //////////////// if (! (mg.isAbstract() || mg.isNative()) ) { // IF mg HAS CODE (See pass 2) - ControlFlowGraph cfg = new ControlFlowGraph(mg); + final ControlFlowGraph cfg = new ControlFlowGraph(mg); // Build the initial frame situation for this method. - Frame f = new Frame(mg.getMaxLocals(),mg.getMaxStack()); + final Frame f = new Frame(mg.getMaxLocals(),mg.getMaxStack()); if ( !mg.isStatic() ) { if (mg.getName().equals(Const.CONSTRUCTOR_NAME)) { Frame.setThis(new UninitializedObjectType(ObjectType.getInstance(jc.getClassName()))); @@ -358,7 +362,7 @@ public final class Pass3bVerifier extends PassVerifier{ f.getLocals().set(0, ObjectType.getInstance(jc.getClassName())); } } - Type[] argtypes = mg.getArgumentTypes(); + final Type[] argtypes = mg.getArgumentTypes(); int twoslotoffset = 0; for (int j=0; j<argtypes.length; j++) { if (argtypes[j] == Type.SHORT || argtypes[j] == Type.BYTE || @@ -374,15 +378,15 @@ public final class Pass3bVerifier extends PassVerifier{ circulationPump(mg,cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev); } } - catch (VerifierConstraintViolatedException ce) { + catch (final VerifierConstraintViolatedException ce) { ce.extendMessage("Constraint violated in method '"+methods[method_no]+"':\n",""); return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage()); } - catch (RuntimeException re) { + catch (final RuntimeException re) { // These are internal errors - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw); re.printStackTrace(pw); throw new AssertionViolatedException("Some RuntimeException occured while verify()ing class '"+jc.getClassName()+ diff --git a/src/main/java/org/apache/bcel/verifier/structurals/Subroutines.java b/src/main/java/org/apache/bcel/verifier/structurals/Subroutines.java index 6ee450bd..19668348 100644 --- a/src/main/java/org/apache/bcel/verifier/structurals/Subroutines.java +++ b/src/main/java/org/apache/bcel/verifier/structurals/Subroutines.java @@ -115,7 +115,7 @@ public class Subroutines{ */ @Override public String toString() { - StringBuilder ret = new StringBuilder(); + final StringBuilder ret = new StringBuilder(); ret.append("Subroutine: Local variable is '").append(localVariable); ret.append("', JSRs are '").append(theJSRs); ret.append("', RET is '").append(theRET); @@ -123,14 +123,14 @@ public class Subroutines{ ret.append(" Accessed local variable slots: '"); int[] alv = getAccessedLocalsIndices(); - for (int element : alv) { + for (final int element : alv) { ret.append(element);ret.append(" "); } ret.append("'."); ret.append(" Recursively (via subsub...routines) accessed local variable slots: '"); alv = getRecursivelyAccessedLocalsIndices(); - for (int element : alv) { + for (final int element : alv) { ret.append(element);ret.append(" "); } ret.append("'."); @@ -148,7 +148,7 @@ public class Subroutines{ "setLeavingRET() called for top-level 'subroutine' or forgot to set local variable first."); } InstructionHandle ret = null; - for (InstructionHandle actual : instructions) { + for (final InstructionHandle actual : instructions) { if (actual.getInstruction() instanceof RET) { if (ret != null) { throw new StructuralCodeConstraintException( @@ -175,7 +175,7 @@ public class Subroutines{ if (this == getTopLevel()) { throw new AssertionViolatedException("getLeavingRET() called on top level pseudo-subroutine."); } - InstructionHandle[] jsrs = new InstructionHandle[theJSRs.size()]; + final InstructionHandle[] jsrs = new InstructionHandle[theJSRs.size()]; return theJSRs.toArray(jsrs); } @@ -214,7 +214,7 @@ public class Subroutines{ */ @Override public InstructionHandle[] getInstructions() { - InstructionHandle[] ret = new InstructionHandle[instructions.size()]; + final InstructionHandle[] ret = new InstructionHandle[instructions.size()]; return instructions.toArray(ret); } @@ -233,15 +233,15 @@ public class Subroutines{ /* Satisfies Subroutine.getRecursivelyAccessedLocalsIndices(). */ @Override public int[] getRecursivelyAccessedLocalsIndices() { - Set<Integer> s = new HashSet<>(); - int[] lvs = getAccessedLocalsIndices(); - for (int lv : lvs) { + final Set<Integer> s = new HashSet<>(); + final int[] lvs = getAccessedLocalsIndices(); + for (final int lv : lvs) { s.add(Integer.valueOf(lv)); } _getRecursivelyAccessedLocalsIndicesHelper(s, this.subSubs()); - int[] ret = new int[s.size()]; + final int[] ret = new int[s.size()]; int j=-1; - for (Integer index : s) { + for (final Integer index : s) { j++; ret[j] = index.intValue(); } @@ -253,9 +253,9 @@ public class Subroutines{ * @see #getRecursivelyAccessedLocalsIndices() */ private void _getRecursivelyAccessedLocalsIndicesHelper(final Set<Integer> s, final Subroutine[] subs) { - for (Subroutine sub : subs) { - int[] lvs = sub.getAccessedLocalsIndices(); - for (int lv : lvs) { + for (final Subroutine sub : subs) { + final int[] lvs = sub.getAccessedLocalsIndices(); + for (final int lv : lvs) { s.add(Integer.valueOf(lv)); } if(sub.subSubs().length != 0) { @@ -270,29 +270,29 @@ public class Subroutines{ @Override public int[] getAccessedLocalsIndices() { //TODO: Implement caching. - Set<Integer> acc = new HashSet<>(); + final Set<Integer> acc = new HashSet<>(); if (theRET == null && this != getTopLevel()) { throw new AssertionViolatedException( "This subroutine object must be built up completely before calculating accessed locals."); } { - for (InstructionHandle ih : instructions) { + for (final InstructionHandle ih : instructions) { // RET is not a LocalVariableInstruction in the current version of BCEL. if (ih.getInstruction() instanceof LocalVariableInstruction || ih.getInstruction() instanceof RET) { - int idx = ((IndexedInstruction) (ih.getInstruction())).getIndex(); + final int idx = ((IndexedInstruction) (ih.getInstruction())).getIndex(); acc.add(Integer.valueOf(idx)); // LONG? DOUBLE?. try{ // LocalVariableInstruction instances are typed without the need to look into // the constant pool. if (ih.getInstruction() instanceof LocalVariableInstruction) { - int s = ((LocalVariableInstruction) ih.getInstruction()).getType(null).getSize(); + final int s = ((LocalVariableInstruction) ih.getInstruction()).getType(null).getSize(); if (s==2) { acc.add(Integer.valueOf(idx+1)); } } } - catch(RuntimeException re) { + catch(final RuntimeException re) { throw new AssertionViolatedException("Oops. BCEL did not like NULL as a ConstantPoolGen object.", re); } } @@ -300,9 +300,9 @@ public class Subroutines{ } { - int[] ret = new int[acc.size()]; + final int[] ret = new int[acc.size()]; int j=-1; - for (Integer accessedLocal : acc) { + for (final Integer accessedLocal : acc) { j++; ret[j] = accessedLocal.intValue(); } @@ -315,16 +315,16 @@ public class Subroutines{ */ @Override public Subroutine[] subSubs() { - Set<Subroutine> h = new HashSet<>(); + final Set<Subroutine> h = new HashSet<>(); - for (InstructionHandle ih : instructions) { - Instruction inst = ih.getInstruction(); + for (final InstructionHandle ih : instructions) { + final Instruction inst = ih.getInstruction(); if (inst instanceof JsrInstruction) { - InstructionHandle targ = ((JsrInstruction) inst).getTarget(); + final InstructionHandle targ = ((JsrInstruction) inst).getTarget(); h.add(getSubroutine(targ)); } } - Subroutine[] ret = new Subroutine[h.size()]; + final Subroutine[] ret = new Subroutine[h.size()]; return h.toArray(ret); } @@ -391,24 +391,24 @@ public class Subroutines{ * @since 6.0 */ public Subroutines(final MethodGen mg, final boolean enableJustIceCheck) { - InstructionHandle[] all = mg.getInstructionList().getInstructionHandles(); - CodeExceptionGen[] handlers = mg.getExceptionHandlers(); + final InstructionHandle[] all = mg.getInstructionList().getInstructionHandles(); + final CodeExceptionGen[] handlers = mg.getExceptionHandlers(); // Define our "Toplevel" fake subroutine. TOPLEVEL = new SubroutineImpl(); // Calculate "real" subroutines. - Set<InstructionHandle> sub_leaders = new HashSet<>(); // Elements: InstructionHandle - for (InstructionHandle element : all) { - Instruction inst = element.getInstruction(); + final Set<InstructionHandle> sub_leaders = new HashSet<>(); // Elements: InstructionHandle + for (final InstructionHandle element : all) { + final Instruction inst = element.getInstruction(); if (inst instanceof JsrInstruction) { sub_leaders.add(((JsrInstruction) inst).getTarget()); } } // Build up the database. - for (InstructionHandle astore : sub_leaders) { - SubroutineImpl sr = new SubroutineImpl(); + for (final InstructionHandle astore : sub_leaders) { + final SubroutineImpl sr = new SubroutineImpl(); sr.setLocalVariable( ((ASTORE) (astore.getInstruction())).getIndex() ); subroutines.put(astore, sr); } @@ -422,10 +422,10 @@ public class Subroutines{ // since "Jsr 0" is disallowed in Pass 3a. // Instructions shared by a subroutine and the toplevel are // disallowed and checked below, after the BFS. - for (InstructionHandle element : all) { - Instruction inst = element.getInstruction(); + for (final InstructionHandle element : all) { + final Instruction inst = element.getInstruction(); if (inst instanceof JsrInstruction) { - InstructionHandle leader = ((JsrInstruction) inst).getTarget(); + final InstructionHandle leader = ((JsrInstruction) inst).getTarget(); ((SubroutineImpl) getSubroutine(leader)).addEnteringJsrInstruction(element); } } @@ -433,16 +433,16 @@ public class Subroutines{ // Now do a BFS from every subroutine leader to find all the // instructions that belong to a subroutine. // we don't want to assign an instruction to two or more Subroutine objects. - Set<InstructionHandle> instructions_assigned = new HashSet<>(); + final Set<InstructionHandle> instructions_assigned = new HashSet<>(); //Graph colouring. Key: InstructionHandle, Value: ColourConstants enum . - Map<InstructionHandle, ColourConstants> colors = new HashMap<>(); + final Map<InstructionHandle, ColourConstants> colors = new HashMap<>(); - List<InstructionHandle> Q = new ArrayList<>(); - for (InstructionHandle actual : sub_leaders) { + final List<InstructionHandle> Q = new ArrayList<>(); + for (final InstructionHandle actual : sub_leaders) { // Do some BFS with "actual" as the root of the graph. // Init colors - for (InstructionHandle element : all) { + for (final InstructionHandle element : all) { colors.put(element, ColourConstants.WHITE); } colors.put(actual, ColourConstants.GRAY); @@ -458,7 +458,7 @@ public class Subroutines{ * TODO: Refer to the special JustIce notion of subroutines.] */ if (actual == all[0]) { - for (CodeExceptionGen handler : handlers) { + for (final CodeExceptionGen handler : handlers) { colors.put(handler.getHandlerPC(), ColourConstants.GRAY); Q.add(handler.getHandlerPC()); } @@ -467,9 +467,9 @@ public class Subroutines{ // Loop until Queue is empty while (Q.size() != 0) { - InstructionHandle u = Q.remove(0); - InstructionHandle[] successors = getSuccessors(u); - for (InstructionHandle successor : successors) { + final InstructionHandle u = Q.remove(0); + final InstructionHandle[] successors = getSuccessors(u); + for (final InstructionHandle successor : successors) { if (colors.get(successor) == ColourConstants.WHITE) { colors.put(successor, ColourConstants.GRAY); Q.add(successor); @@ -478,7 +478,7 @@ public class Subroutines{ colors.put(u, ColourConstants.BLACK); } // BFS ended above. - for (InstructionHandle element : all) { + for (final InstructionHandle element : all) { if (colors.get(element) == ColourConstants.BLACK) { ((SubroutineImpl) (actual==all[0]?getTopLevel():getSubroutine(actual))).addInstruction(element); if (instructions_assigned.contains(element)) { @@ -496,11 +496,11 @@ public class Subroutines{ if (enableJustIceCheck) { // Now make sure no instruction of a Subroutine is protected by exception handling code // as is mandated by JustIces notion of subroutines. - for (CodeExceptionGen handler : handlers) { + for (final CodeExceptionGen handler : handlers) { InstructionHandle _protected = handler.getStartPC(); while (_protected != handler.getEndPC().getNext()) { // Note the inclusive/inclusive notation of "generic API" exception handlers! - for (Subroutine sub : subroutines.values()) { + for (final Subroutine sub : subroutines.values()) { if (sub != subroutines.get(all[0])) { // We don't want to forbid top-level exception handlers. if (sub.contains(_protected)) { throw new StructuralCodeConstraintException("Subroutine instruction '"+_protected+ @@ -536,14 +536,14 @@ public class Subroutines{ * @throws StructuralCodeConstraintException if the above constraint is not satisfied. */ private void noRecursiveCalls(final Subroutine sub, final Set<Integer> set) { - Subroutine[] subs = sub.subSubs(); + final Subroutine[] subs = sub.subSubs(); - for (Subroutine sub2 : subs) { - int index = ((RET) (sub2.getLeavingRET().getInstruction())).getIndex(); + for (final Subroutine sub2 : subs) { + final int index = ((RET) (sub2.getLeavingRET().getInstruction())).getIndex(); if (!set.add(Integer.valueOf(index))) { // Don't use toString() here because of possibly infinite recursive subSubs() calls then. - SubroutineImpl si = (SubroutineImpl) sub2; + final SubroutineImpl si = (SubroutineImpl) sub2; throw new StructuralCodeConstraintException("Subroutine with local variable '"+si.localVariable+"', JSRs '"+ si.theJSRs+"', RET '"+si.theRET+ "' is called by a subroutine which uses the same local variable index as itself; maybe even a recursive call?"+ @@ -565,7 +565,7 @@ public class Subroutines{ * @see #getTopLevel() */ public Subroutine getSubroutine(final InstructionHandle leader) { - Subroutine ret = subroutines.get(leader); + final Subroutine ret = subroutines.get(leader); if (ret == null) { throw new AssertionViolatedException( @@ -591,7 +591,7 @@ public class Subroutines{ * @see #getTopLevel() */ public Subroutine subroutineOf(final InstructionHandle any) { - for (Subroutine s : subroutines.values()) { + for (final Subroutine s : subroutines.values()) { if (s.contains(any)) { return s; } @@ -624,7 +624,7 @@ System.err.println("DEBUG: Please verify '"+any.toString(true)+"' lies in dead c final InstructionHandle[] empty = new InstructionHandle[0]; final InstructionHandle[] single = new InstructionHandle[1]; - Instruction inst = instruction.getInstruction(); + final Instruction inst = instruction.getInstruction(); if (inst instanceof RET) { return empty; @@ -656,8 +656,8 @@ System.err.println("DEBUG: Please verify '"+any.toString(true)+"' lies in dead c if (inst instanceof Select) { // BCEL's getTargets() returns only the non-default targets, // thanks to Eli Tilevich for reporting. - InstructionHandle[] matchTargets = ((Select) inst).getTargets(); - InstructionHandle[] ret = new InstructionHandle[matchTargets.length+1]; + final InstructionHandle[] matchTargets = ((Select) inst).getTargets(); + final InstructionHandle[] ret = new InstructionHandle[matchTargets.length+1]; ret[0] = ((Select) inst).getTarget(); System.arraycopy(matchTargets, 0, ret, 1, matchTargets.length); return ret; diff --git a/src/test/java/org/apache/bcel/AbstractTestCase.java b/src/test/java/org/apache/bcel/AbstractTestCase.java index e1b9357c..4cf22b3c 100644 --- a/src/test/java/org/apache/bcel/AbstractTestCase.java +++ b/src/test/java/org/apache/bcel/AbstractTestCase.java @@ -65,8 +65,8 @@ public abstract class AbstractTestCase extends TestCase protected Method getMethod(final JavaClass cl, final String methodname) { - Method[] methods = cl.getMethods(); - for (Method m : methods) { + final Method[] methods = cl.getMethods(); + for (final Method m : methods) { if (m.getName().equals(methodname)) { return m; @@ -94,9 +94,9 @@ public abstract class AbstractTestCase extends TestCase protected boolean wipe(final String dir, final String name) { // The parameter is relative to the TESTDATA dir - boolean b = wipe(dir + File.separator + name); + final boolean b = wipe(dir + File.separator + name); final File testDir = new File(TESTDATA, dir); - String[] files = testDir.list(); + final String[] files = testDir.list(); if (files == null || files.length == 0) { if (!testDir.delete()) { @@ -110,16 +110,16 @@ public abstract class AbstractTestCase extends TestCase public SyntheticRepository createRepos(final String cpentry) { - ClassPath cp = new ClassPath("target" + File.separator + "testdata" + final ClassPath cp = new ClassPath("target" + File.separator + "testdata" + File.separator + cpentry + File.separator); return SyntheticRepository.getInstance(cp); } protected Attribute[] findAttribute(final String name, final JavaClass clazz) { - Attribute[] all = clazz.getAttributes(); - List<Attribute> chosenAttrsList = new ArrayList<>(); - for (Attribute element : all) { + final Attribute[] all = clazz.getAttributes(); + final List<Attribute> chosenAttrsList = new ArrayList<>(); + for (final Attribute element : all) { if (verbose) { System.err.println("Attribute: " + element.getName()); } @@ -132,8 +132,8 @@ public abstract class AbstractTestCase extends TestCase protected Attribute findAttribute(final String name, final Attribute[] all) { - List<Attribute> chosenAttrsList = new ArrayList<>(); - for (Attribute element : all) { + final List<Attribute> chosenAttrsList = new ArrayList<>(); + for (final Attribute element : all) { if (verbose) { System.err.println("Attribute: " + element.getName()); } @@ -148,11 +148,11 @@ public abstract class AbstractTestCase extends TestCase protected String dumpAttributes(final Attribute[] as) { - StringBuilder result = new StringBuilder(); + final StringBuilder result = new StringBuilder(); result.append("AttributeArray:["); for (int i = 0; i < as.length; i++) { - Attribute attr = as[i]; + final Attribute attr = as[i]; result.append(attr.toString()); if (i + 1 < as.length) { result.append(","); @@ -164,11 +164,11 @@ public abstract class AbstractTestCase extends TestCase protected String dumpAnnotationEntries(final AnnotationEntry[] as) { - StringBuilder result = new StringBuilder(); + final StringBuilder result = new StringBuilder(); result.append("["); for (int i = 0; i < as.length; i++) { - AnnotationEntry annotation = as[i]; + final AnnotationEntry annotation = as[i]; result.append(annotation.toShortString()); if (i + 1 < as.length) { result.append(","); @@ -180,11 +180,11 @@ public abstract class AbstractTestCase extends TestCase protected String dumpAnnotationEntries(final AnnotationEntryGen[] as) { - StringBuilder result = new StringBuilder(); + final StringBuilder result = new StringBuilder(); result.append("["); for (int i = 0; i < as.length; i++) { - AnnotationEntryGen annotation = as[i]; + final AnnotationEntryGen annotation = as[i]; result.append(annotation.toShortString()); if (i + 1 < as.length) { result.append(","); @@ -197,11 +197,11 @@ public abstract class AbstractTestCase extends TestCase public AnnotationEntryGen createFruitAnnotationEntry(final ConstantPoolGen cp, final String aFruit, final boolean visibility) { - SimpleElementValueGen evg = new SimpleElementValueGen( + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.STRING, cp, aFruit); - ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp); - ObjectType t = new ObjectType("SimpleStringAnnotation"); - List<ElementValuePairGen> elements = new ArrayList<>(); + final ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp); + final ObjectType t = new ObjectType("SimpleStringAnnotation"); + final List<ElementValuePairGen> elements = new ArrayList<>(); elements.add(nvGen); return new AnnotationEntryGen(t, elements, visibility, cp); } diff --git a/src/test/java/org/apache/bcel/AnnotationDefaultAttributeTestCase.java b/src/test/java/org/apache/bcel/AnnotationDefaultAttributeTestCase.java index 6afe6794..e80afb33 100644 --- a/src/test/java/org/apache/bcel/AnnotationDefaultAttributeTestCase.java +++ b/src/test/java/org/apache/bcel/AnnotationDefaultAttributeTestCase.java @@ -33,11 +33,11 @@ public class AnnotationDefaultAttributeTestCase extends AbstractTestCase */ public void testMethodAnnotations() throws ClassNotFoundException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation"); - Method m = getMethod(clazz, "fruit"); - AnnotationDefault a = (AnnotationDefault) findAttribute( + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotation"); + final Method m = getMethod(clazz, "fruit"); + final AnnotationDefault a = (AnnotationDefault) findAttribute( "AnnotationDefault", m.getAttributes()); - SimpleElementValue val = (SimpleElementValue) a.getDefaultValue(); + final SimpleElementValue val = (SimpleElementValue) a.getDefaultValue(); assertTrue("Should be STRING but is " + val.getElementValueType(), val .getElementValueType() == ElementValue.STRING); assertTrue("Should have default of bananas but default is " diff --git a/src/test/java/org/apache/bcel/AnonymousClassTestCase.java b/src/test/java/org/apache/bcel/AnonymousClassTestCase.java index 6506d63d..ae81271f 100644 --- a/src/test/java/org/apache/bcel/AnonymousClassTestCase.java +++ b/src/test/java/org/apache/bcel/AnonymousClassTestCase.java @@ -24,7 +24,7 @@ public class AnonymousClassTestCase extends AbstractTestCase { public void testRegularClassIsNotAnonymous() throws ClassNotFoundException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnonymousClassTest"); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnonymousClassTest"); assertFalse("regular outer classes are not anonymous", clazz .isAnonymous()); assertFalse("regular outer classes are not nested", clazz.isNested()); @@ -33,7 +33,7 @@ public class AnonymousClassTestCase extends AbstractTestCase public void testNamedInnerClassIsNotAnonymous() throws ClassNotFoundException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnonymousClassTest$X"); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnonymousClassTest$X"); assertFalse("regular inner classes are not anonymous", clazz .isAnonymous()); assertTrue("regular inner classes are nested", clazz.isNested()); @@ -42,7 +42,7 @@ public class AnonymousClassTestCase extends AbstractTestCase public void testStaticInnerClassIsNotAnonymous() throws ClassNotFoundException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnonymousClassTest$Y"); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnonymousClassTest$Y"); assertFalse("regular static inner classes are not anonymous", clazz .isAnonymous()); assertTrue("regular static inner classes are nested", clazz.isNested()); @@ -51,7 +51,7 @@ public class AnonymousClassTestCase extends AbstractTestCase public void testAnonymousInnerClassIsAnonymous() throws ClassNotFoundException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnonymousClassTest$1"); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnonymousClassTest$1"); assertTrue("anonymous inner classes are anonymous", clazz.isAnonymous()); assertTrue("anonymous inner classes are anonymous", clazz.isNested()); } diff --git a/src/test/java/org/apache/bcel/ElementValueGenTestCase.java b/src/test/java/org/apache/bcel/ElementValueGenTestCase.java index 107f5d34..0293f45c 100644 --- a/src/test/java/org/apache/bcel/ElementValueGenTestCase.java +++ b/src/test/java/org/apache/bcel/ElementValueGenTestCase.java @@ -45,9 +45,9 @@ public class ElementValueGenTestCase extends AbstractTestCase */ public void testCreateIntegerElementValue() throws Exception { - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - SimpleElementValueGen evg = new SimpleElementValueGen( + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_INT, cp, 555); // Creation of an element like that should leave a new entry in the // cpool @@ -59,9 +59,9 @@ public class ElementValueGenTestCase extends AbstractTestCase public void testCreateFloatElementValue() throws Exception { - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - SimpleElementValueGen evg = new SimpleElementValueGen( + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_FLOAT, cp, 111.222f); // Creation of an element like that should leave a new entry in the // cpool @@ -73,13 +73,13 @@ public class ElementValueGenTestCase extends AbstractTestCase public void testCreateDoubleElementValue() throws Exception { - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - SimpleElementValueGen evg = new SimpleElementValueGen( + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_DOUBLE, cp, 333.44); // Creation of an element like that should leave a new entry in the // cpool - int idx = cp.lookupDouble(333.44); + final int idx = cp.lookupDouble(333.44); assertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx); checkSerialize(evg, cp); @@ -87,13 +87,13 @@ public class ElementValueGenTestCase extends AbstractTestCase public void testCreateLongElementValue() throws Exception { - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - SimpleElementValueGen evg = new SimpleElementValueGen( + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_LONG, cp, 3334455L); // Creation of an element like that should leave a new entry in the // cpool - int idx = cp.lookupLong(3334455L); + final int idx = cp.lookupLong(3334455L); assertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx); checkSerialize(evg, cp); @@ -101,13 +101,13 @@ public class ElementValueGenTestCase extends AbstractTestCase public void testCreateCharElementValue() throws Exception { - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - SimpleElementValueGen evg = new SimpleElementValueGen( + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_CHAR, cp, 't'); // Creation of an element like that should leave a new entry in the // cpool - int idx = cp.lookupInteger('t'); + final int idx = cp.lookupInteger('t'); assertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx); checkSerialize(evg, cp); @@ -115,13 +115,13 @@ public class ElementValueGenTestCase extends AbstractTestCase public void testCreateByteElementValue() throws Exception { - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - SimpleElementValueGen evg = new SimpleElementValueGen( + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_CHAR, cp, (byte) 'z'); // Creation of an element like that should leave a new entry in the // cpool - int idx = cp.lookupInteger((byte) 'z'); + final int idx = cp.lookupInteger((byte) 'z'); assertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx); checkSerialize(evg, cp); @@ -129,13 +129,13 @@ public class ElementValueGenTestCase extends AbstractTestCase public void testCreateBooleanElementValue() throws Exception { - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - SimpleElementValueGen evg = new SimpleElementValueGen( + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_BOOLEAN, cp, true); // Creation of an element like that should leave a new entry in the // cpool - int idx = cp.lookupInteger(1); // 1 == true + final int idx = cp.lookupInteger(1); // 1 == true assertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx); checkSerialize(evg, cp); @@ -143,13 +143,13 @@ public class ElementValueGenTestCase extends AbstractTestCase public void testCreateShortElementValue() throws Exception { - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - SimpleElementValueGen evg = new SimpleElementValueGen( + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_SHORT, cp, (short) 42); // Creation of an element like that should leave a new entry in the // cpool - int idx = cp.lookupInteger(42); + final int idx = cp.lookupInteger(42); assertTrue("Should have the same index in the constantpool but " + evg.getIndex() + "!=" + idx, evg.getIndex() == idx); checkSerialize(evg, cp); @@ -160,9 +160,9 @@ public class ElementValueGenTestCase extends AbstractTestCase public void testCreateStringElementValue() throws Exception { // Create HelloWorld - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - SimpleElementValueGen evg = new SimpleElementValueGen( + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.STRING, cp, "hello"); // Creation of an element like that should leave a new entry in the // cpool @@ -176,11 +176,11 @@ public class ElementValueGenTestCase extends AbstractTestCase // Create enum element value public void testCreateEnumElementValue() throws Exception { - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - ObjectType enumType = new ObjectType("SimpleEnum"); // Supports rainbow + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final ObjectType enumType = new ObjectType("SimpleEnum"); // Supports rainbow // :) - EnumElementValueGen evg = new EnumElementValueGen(enumType, "Red", cp); + final EnumElementValueGen evg = new EnumElementValueGen(enumType, "Red", cp); // Creation of an element like that should leave a new entry in the // cpool assertTrue( @@ -200,18 +200,18 @@ public class ElementValueGenTestCase extends AbstractTestCase // Create class element value public void testCreateClassElementValue() throws Exception { - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - ObjectType classType = new ObjectType("java.lang.Integer"); - ClassElementValueGen evg = new ClassElementValueGen(classType, cp); + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final ObjectType classType = new ObjectType("java.lang.Integer"); + final ClassElementValueGen evg = new ClassElementValueGen(classType, cp); assertTrue("Unexpected value for contained class: '" + evg.getClassString() + "'", evg.getClassString().contains("Integer")); checkSerialize(evg, cp); } private void checkSerialize(final ElementValueGen evgBefore, final ConstantPoolGen cpg) throws IOException { - String beforeValue = evgBefore.stringifyValue(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final String beforeValue = evgBefore.stringifyValue(); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(baos)) { evgBefore.dump(dos); dos.flush(); @@ -220,7 +220,7 @@ public class ElementValueGenTestCase extends AbstractTestCase try (DataInputStream dis = new DataInputStream(new ByteArrayInputStream(baos.toByteArray()))) { evgAfter = ElementValueGen.readElementValue(dis, cpg); } - String afterValue = evgAfter.stringifyValue(); + final String afterValue = evgAfter.stringifyValue(); if (!beforeValue.equals(afterValue)) { fail("Deserialization failed: before='" + beforeValue + "' after='" + afterValue + "'"); } diff --git a/src/test/java/org/apache/bcel/EnclosingMethodAttributeTestCase.java b/src/test/java/org/apache/bcel/EnclosingMethodAttributeTestCase.java index 80f0c36b..1672cbf3 100644 --- a/src/test/java/org/apache/bcel/EnclosingMethodAttributeTestCase.java +++ b/src/test/java/org/apache/bcel/EnclosingMethodAttributeTestCase.java @@ -37,14 +37,14 @@ public class EnclosingMethodAttributeTestCase extends AbstractTestCase public void testCheckMethodLevelNamedInnerClass() throws ClassNotFoundException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM01$1S"); - ConstantPool pool = clazz.getConstantPool(); - Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM01$1S"); + final ConstantPool pool = clazz.getConstantPool(); + final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz); assertTrue("Expected 1 EnclosingMethod attribute but found " + encMethodAttrs.length, encMethodAttrs.length == 1); - EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0]; - String enclosingClassName = em.getEnclosingClass().getBytes(pool); - String enclosingMethodName = em.getEnclosingMethod().getName(pool); + final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0]; + final String enclosingClassName = em.getEnclosingClass().getBytes(pool); + final String enclosingMethodName = em.getEnclosingMethod().getName(pool); assertTrue( "Expected class name to be '"+PACKAGE_BASE_SIG+"/data/AttributeTestClassEM01' but was " + enclosingClassName, enclosingClassName @@ -60,13 +60,13 @@ public class EnclosingMethodAttributeTestCase extends AbstractTestCase public void testCheckClassLevelNamedInnerClass() throws ClassNotFoundException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM02$1"); - ConstantPool pool = clazz.getConstantPool(); - Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM02$1"); + final ConstantPool pool = clazz.getConstantPool(); + final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz); assertTrue("Expected 1 EnclosingMethod attribute but found " + encMethodAttrs.length, encMethodAttrs.length == 1); - EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0]; - String enclosingClassName = em.getEnclosingClass().getBytes(pool); + final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0]; + final String enclosingClassName = em.getEnclosingClass().getBytes(pool); assertTrue( "The class is not within a method, so method_index should be null, but it is " + em.getEnclosingMethodIndex(), em @@ -83,20 +83,20 @@ public class EnclosingMethodAttributeTestCase extends AbstractTestCase public void testAttributeSerializtion() throws ClassNotFoundException, IOException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM02$1"); - ConstantPool pool = clazz.getConstantPool(); - Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AttributeTestClassEM02$1"); + final ConstantPool pool = clazz.getConstantPool(); + final Attribute[] encMethodAttrs = findAttribute("EnclosingMethod", clazz); assertTrue("Expected 1 EnclosingMethod attribute but found " + encMethodAttrs.length, encMethodAttrs.length == 1); // Write it out - File tfile = createTestdataFile("AttributeTestClassEM02$1.class"); + final File tfile = createTestdataFile("AttributeTestClassEM02$1.class"); clazz.dump(tfile); // Read in the new version and check it is OK - SyntheticRepository repos2 = createRepos("."); - JavaClass clazz2 = repos2.loadClass("AttributeTestClassEM02$1"); + final SyntheticRepository repos2 = createRepos("."); + final JavaClass clazz2 = repos2.loadClass("AttributeTestClassEM02$1"); Assert.assertNotNull(clazz2); // Use the variable to avoid a warning - EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0]; - String enclosingClassName = em.getEnclosingClass().getBytes(pool); + final EnclosingMethod em = (EnclosingMethod) encMethodAttrs[0]; + final String enclosingClassName = em.getEnclosingClass().getBytes(pool); assertTrue( "The class is not within a method, so method_index should be null, but it is " + em.getEnclosingMethodIndex(), em diff --git a/src/test/java/org/apache/bcel/InstructionFinderTestCase.java b/src/test/java/org/apache/bcel/InstructionFinderTestCase.java index 6feb1911..ec4469ff 100644 --- a/src/test/java/org/apache/bcel/InstructionFinderTestCase.java +++ b/src/test/java/org/apache/bcel/InstructionFinderTestCase.java @@ -29,10 +29,10 @@ public class InstructionFinderTestCase extends AbstractTestCase { public void testSearchAll() throws Exception { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".util.InstructionFinder"); - Method[] methods = clazz.getMethods(); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".util.InstructionFinder"); + final Method[] methods = clazz.getMethods(); Method searchM = null; - for (Method m : methods) + for (final Method m : methods) { if (m.getName().equals("search") && (m.getArgumentTypes().length == 3)) { @@ -45,14 +45,14 @@ public class InstructionFinderTestCase extends AbstractTestCase throw new Exception("search method not found"); } - byte[] bytes = searchM.getCode().getCode(); - InstructionList il = new InstructionList(bytes); - InstructionFinder finder = new InstructionFinder(il); - Iterator<?> it = finder.search(".*", il.getStart(), null); + final byte[] bytes = searchM.getCode().getCode(); + final InstructionList il = new InstructionList(bytes); + final InstructionFinder finder = new InstructionFinder(il); + final Iterator<?> it = finder.search(".*", il.getStart(), null); - InstructionHandle[] ihs = (InstructionHandle[])it.next(); + final InstructionHandle[] ihs = (InstructionHandle[])it.next(); int size = 0; - for (InstructionHandle ih : ihs) + for (final InstructionHandle ih : ihs) { size += ih.getInstruction().getLength(); } diff --git a/src/test/java/org/apache/bcel/PLSETestCase.java b/src/test/java/org/apache/bcel/PLSETestCase.java index f30a5feb..0fda519a 100644 --- a/src/test/java/org/apache/bcel/PLSETestCase.java +++ b/src/test/java/org/apache/bcel/PLSETestCase.java @@ -34,11 +34,11 @@ public class PLSETestCase extends AbstractTestCase */ public void testB208() throws ClassNotFoundException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass"); - ClassGen gen = new ClassGen(clazz); - ConstantPoolGen pool = gen.getConstantPool(); - Method m = gen.getMethodAt(1); - MethodGen mg = new MethodGen(m, gen.getClassName(), pool); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass"); + final ClassGen gen = new ClassGen(clazz); + final ConstantPoolGen pool = gen.getConstantPool(); + final Method m = gen.getMethodAt(1); + final MethodGen mg = new MethodGen(m, gen.getClassName(), pool); mg.setInstructionList(null); mg.addLocalVariable("local2", Type.INT, null, null); // currently, this will cause null pointer exception @@ -50,15 +50,15 @@ public class PLSETestCase extends AbstractTestCase */ public void testB79() throws ClassNotFoundException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass"); - ClassGen gen = new ClassGen(clazz); - ConstantPoolGen pool = gen.getConstantPool(); - Method m = gen.getMethodAt(2); - LocalVariableTable lvt = m.getLocalVariableTable(); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.PLSETestClass"); + final ClassGen gen = new ClassGen(clazz); + final ConstantPoolGen pool = gen.getConstantPool(); + final Method m = gen.getMethodAt(2); + final LocalVariableTable lvt = m.getLocalVariableTable(); //System.out.println(lvt); //System.out.println(lvt.getTableLength()); - MethodGen mg = new MethodGen(m, gen.getClassName(), pool); - LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool()); + final MethodGen mg = new MethodGen(m, gen.getClassName(), pool); + final LocalVariableTable new_lvt = mg.getLocalVariableTable(mg.getConstantPool()); //System.out.println(new_lvt); assertEquals("number of locals", lvt.getTableLength(), new_lvt.getTableLength()); } diff --git a/src/test/java/org/apache/bcel/PerformanceTest.java b/src/test/java/org/apache/bcel/PerformanceTest.java index d5c3a62d..0c08d795 100644 --- a/src/test/java/org/apache/bcel/PerformanceTest.java +++ b/src/test/java/org/apache/bcel/PerformanceTest.java @@ -48,10 +48,10 @@ public final class PerformanceTest extends TestCase { byte[] b = new byte[is.available()]; int len = 0; while (true) { - int n = is.read(b, len, b.length - len); + final int n = is.read(b, len, b.length - len); if (n == -1) { if (len < b.length) { - byte[] c = new byte[len]; + final byte[] c = new byte[len]; System.arraycopy(b, 0, c, 0, len); b = c; } @@ -59,7 +59,7 @@ public final class PerformanceTest extends TestCase { } len += n; if (len == b.length) { - byte[] c = new byte[b.length + 1000]; + final byte[] c = new byte[b.length + 1000]; System.arraycopy(b, 0, c, 0, len); b = c; } @@ -67,21 +67,21 @@ public final class PerformanceTest extends TestCase { } private static void test(final File lib) throws IOException { - NanoTimer total = new NanoTimer(); - NanoTimer parseTime = new NanoTimer(); - NanoTimer cgenTime = new NanoTimer(); - NanoTimer mgenTime = new NanoTimer(); - NanoTimer mserTime = new NanoTimer(); - NanoTimer serTime = new NanoTimer(); + final NanoTimer total = new NanoTimer(); + final NanoTimer parseTime = new NanoTimer(); + final NanoTimer cgenTime = new NanoTimer(); + final NanoTimer mgenTime = new NanoTimer(); + final NanoTimer mserTime = new NanoTimer(); + final NanoTimer serTime = new NanoTimer(); System.out.println("parsing " + lib); total.start(); try (JarFile jar = new JarFile(lib)) { - Enumeration<?> en = jar.entries(); + final Enumeration<?> en = jar.entries(); while (en.hasMoreElements()) { - JarEntry e = (JarEntry) en.nextElement(); + final JarEntry e = (JarEntry) en.nextElement(); if (e.getName().endsWith(".class")) { byte[] bytes; try (InputStream in = jar.getInputStream(e)) { @@ -89,18 +89,18 @@ public final class PerformanceTest extends TestCase { } parseTime.start(); - JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), e.getName()).parse(); + final JavaClass clazz = new ClassParser(new ByteArrayInputStream(bytes), e.getName()).parse(); parseTime.stop(); cgenTime.start(); - ClassGen cg = new ClassGen(clazz); + final ClassGen cg = new ClassGen(clazz); cgenTime.stop(); - Method[] methods = cg.getMethods(); - for (Method m : methods) { + final Method[] methods = cg.getMethods(); + for (final Method m : methods) { mgenTime.start(); - MethodGen mg = new MethodGen(m, cg.getClassName(), cg.getConstantPool()); - InstructionList il = mg.getInstructionList(); + final MethodGen mg = new MethodGen(m, cg.getClassName(), cg.getConstantPool()); + final InstructionList il = mg.getInstructionList(); mgenTime.stop(); mserTime.start(); @@ -132,7 +132,7 @@ public final class PerformanceTest extends TestCase { } public void testPerformance() { - File javaLib = new File(System.getProperty("java.home") + "/lib"); + final File javaLib = new File(System.getProperty("java.home") + "/lib"); javaLib.listFiles(new FileFilter() { @Override @@ -140,7 +140,7 @@ public final class PerformanceTest extends TestCase { if(file.getName().endsWith(".jar")) { try { test(file); - } catch (IOException e) { + } catch (final IOException e) { Assert.fail(e.getMessage()); } } diff --git a/src/test/java/org/apache/bcel/classfile/JDKClassDumpTestCase.java b/src/test/java/org/apache/bcel/classfile/JDKClassDumpTestCase.java index 9810a77f..9bf530e0 100644 --- a/src/test/java/org/apache/bcel/classfile/JDKClassDumpTestCase.java +++ b/src/test/java/org/apache/bcel/classfile/JDKClassDumpTestCase.java @@ -39,7 +39,7 @@ public class JDKClassDumpTestCase { @Test public void testPerformance() throws Exception { - File javaLib = new File(System.getProperty("java.home") + "/lib"); + final File javaLib = new File(System.getProperty("java.home") + "/lib"); javaLib.listFiles(new FileFilter() { @Override @@ -47,7 +47,7 @@ public class JDKClassDumpTestCase { if (file.getName().endsWith(".jar")) { try { testJar(file); - } catch (Exception e) { + } catch (final Exception e) { Assert.fail(e.getMessage()); } } @@ -60,15 +60,15 @@ public class JDKClassDumpTestCase { private void testJar(final File file) throws Exception { System.out.println("parsing " + file); try (JarFile jar = new JarFile(file)) { - Enumeration<JarEntry> en = jar.entries(); + final Enumeration<JarEntry> en = jar.entries(); while (en.hasMoreElements()) { - JarEntry e = en.nextElement(); + final JarEntry e = en.nextElement(); final String name = e.getName(); if (name.endsWith(".class")) { // System.out.println("parsing " + name); try (InputStream in = jar.getInputStream(e)) { - ClassParser parser = new ClassParser(in, name); - JavaClass jc = parser.parse(); + final ClassParser parser = new ClassParser(in, name); + final JavaClass jc = parser.parse(); compare(jc, jar.getInputStream(e), name); } } @@ -83,8 +83,8 @@ public class JDKClassDumpTestCase { } try (DataInputStream src = new DataInputStream(inputStream)) { int i = 0; - for (int out : baos.toByteArray()) { - int in = src.read(); + for (final int out : baos.toByteArray()) { + final int in = src.read(); assertEquals(name + ": Mismatch at " + i, in, out & 0xFF); i++; } diff --git a/src/test/java/org/apache/bcel/data/PLSETestClass.java b/src/test/java/org/apache/bcel/data/PLSETestClass.java index e98cc761..b29f0975 100644 --- a/src/test/java/org/apache/bcel/data/PLSETestClass.java +++ b/src/test/java/org/apache/bcel/data/PLSETestClass.java @@ -25,12 +25,14 @@ public class PLSETestClass public void meth1(final int arg1) { @SuppressWarnings("unused") + final int local1 = arg1; } public void meth2(final int arg1, final ArrayList<String> arg2, final int arg3) { @SuppressWarnings("unused") + final int local1 = arg1; } } diff --git a/src/test/java/org/apache/bcel/generic/AnnotationGenTestCase.java b/src/test/java/org/apache/bcel/generic/AnnotationGenTestCase.java index 1abca694..0d592379 100644 --- a/src/test/java/org/apache/bcel/generic/AnnotationGenTestCase.java +++ b/src/test/java/org/apache/bcel/generic/AnnotationGenTestCase.java @@ -46,24 +46,24 @@ public class AnnotationGenTestCase extends AbstractTestCase public void testConstructMutableAnnotation() { // Create the containing class - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); // Create the simple primitive value '4' of type 'int' - SimpleElementValueGen evg = new SimpleElementValueGen( + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_INT, cp, 4); // Give it a name, call it 'id' - ElementValuePairGen nvGen = new ElementValuePairGen("id", evg, + final ElementValuePairGen nvGen = new ElementValuePairGen("id", evg, cp); // Check it looks right assertTrue( "Should include string 'id=4' but says: " + nvGen.toString(), nvGen.toString().contains("id=4")); - ObjectType t = new ObjectType("SimpleAnnotation"); - List<ElementValuePairGen> elements = new ArrayList<>(); + final ObjectType t = new ObjectType("SimpleAnnotation"); + final List<ElementValuePairGen> elements = new ArrayList<>(); elements.add(nvGen); // Build an annotation of type 'SimpleAnnotation' with 'id=4' as the // only value :) - AnnotationEntryGen a = new AnnotationEntryGen(t, elements, true, cp); + final AnnotationEntryGen a = new AnnotationEntryGen(t, elements, true, cp); // Check we can save and load it ok checkSerialize(a, cp); } @@ -71,29 +71,29 @@ public class AnnotationGenTestCase extends AbstractTestCase public void testVisibleInvisibleAnnotationGen() { // Create the containing class - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); // Create the simple primitive value '4' of type 'int' - SimpleElementValueGen evg = new SimpleElementValueGen( + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_INT, cp, 4); // Give it a name, call it 'id' - ElementValuePairGen nvGen = new ElementValuePairGen("id", evg, + final ElementValuePairGen nvGen = new ElementValuePairGen("id", evg, cp); // Check it looks right assertTrue( "Should include string 'id=4' but says: " + nvGen.toString(), nvGen.toString().contains("id=4")); - ObjectType t = new ObjectType("SimpleAnnotation"); - List<ElementValuePairGen> elements = new ArrayList<>(); + final ObjectType t = new ObjectType("SimpleAnnotation"); + final List<ElementValuePairGen> elements = new ArrayList<>(); elements.add(nvGen); // Build a RV annotation of type 'SimpleAnnotation' with 'id=4' as the // only value :) - AnnotationEntryGen a = new AnnotationEntryGen(t, elements, true, cp); - List<AnnotationEntryGen> v = new ArrayList<>(); + final AnnotationEntryGen a = new AnnotationEntryGen(t, elements, true, cp); + final List<AnnotationEntryGen> v = new ArrayList<>(); v.add(a); - Attribute[] attributes = AnnotationEntryGen.getAnnotationAttributes(cp, v.toArray(new AnnotationEntryGen[0])); + final Attribute[] attributes = AnnotationEntryGen.getAnnotationAttributes(cp, v.toArray(new AnnotationEntryGen[0])); boolean foundRV = false; - for (Attribute attribute : attributes) { + for (final Attribute attribute : attributes) { if (attribute instanceof RuntimeVisibleAnnotations) { assertTrue(((Annotations) attribute).isRuntimeVisible()); @@ -103,12 +103,12 @@ public class AnnotationGenTestCase extends AbstractTestCase assertTrue("Should have seen a RuntimeVisibleAnnotation", foundRV); // Build a RIV annotation of type 'SimpleAnnotation' with 'id=4' as the // only value :) - AnnotationEntryGen a2 = new AnnotationEntryGen(t, elements, false, cp); - List<AnnotationEntryGen> v2 = new ArrayList<>(); + final AnnotationEntryGen a2 = new AnnotationEntryGen(t, elements, false, cp); + final List<AnnotationEntryGen> v2 = new ArrayList<>(); v2.add(a2); - Attribute[] attributes2 = AnnotationEntryGen.getAnnotationAttributes(cp, v2.toArray(new AnnotationEntryGen[0])); + final Attribute[] attributes2 = AnnotationEntryGen.getAnnotationAttributes(cp, v2.toArray(new AnnotationEntryGen[0])); boolean foundRIV = false; - for (Attribute attribute : attributes2) { + for (final Attribute attribute : attributes2) { if (attribute instanceof RuntimeInvisibleAnnotations) { assertFalse(((Annotations) attribute).isRuntimeVisible()); @@ -122,19 +122,19 @@ public class AnnotationGenTestCase extends AbstractTestCase { try { - String beforeName = a.getTypeName(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final String beforeName = a.getTypeName(); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(baos)) { a.dump(dos); dos.flush(); } - byte[] bs = baos.toByteArray(); - ByteArrayInputStream bais = new ByteArrayInputStream(bs); + final byte[] bs = baos.toByteArray(); + final ByteArrayInputStream bais = new ByteArrayInputStream(bs); AnnotationEntryGen annAfter; try (DataInputStream dis = new DataInputStream(bais)) { annAfter = AnnotationEntryGen.read(dis, cpg, a.isRuntimeVisible()); } - String afterName = annAfter.getTypeName(); + final String afterName = annAfter.getTypeName(); if (!beforeName.equals(afterName)) { fail("Deserialization failed: before type='" + beforeName @@ -148,8 +148,8 @@ public class AnnotationGenTestCase extends AbstractTestCase } for (int i = 0; i < a.getValues().size(); i++) { - ElementValuePairGen beforeElement = a.getValues().get(i); - ElementValuePairGen afterElement = annAfter.getValues().get(i); + final ElementValuePairGen beforeElement = a.getValues().get(i); + final ElementValuePairGen afterElement = annAfter.getValues().get(i); if (!beforeElement.getNameString().equals( afterElement.getNameString())) { @@ -158,7 +158,7 @@ public class AnnotationGenTestCase extends AbstractTestCase } } } - catch (IOException ioe) + catch (final IOException ioe) { fail("Unexpected exception whilst checking serialization: " + ioe); } diff --git a/src/test/java/org/apache/bcel/generic/BranchHandleTestCase.java b/src/test/java/org/apache/bcel/generic/BranchHandleTestCase.java index 102d6bcb..b9332590 100644 --- a/src/test/java/org/apache/bcel/generic/BranchHandleTestCase.java +++ b/src/test/java/org/apache/bcel/generic/BranchHandleTestCase.java @@ -25,7 +25,7 @@ public class BranchHandleTestCase { // Test that setInstruction only allows BranchInstructions @Test(expected=ClassGenException.class) public void testsetInstructionNull() { - BranchHandle bh = BranchHandle.getBranchHandle(new GOTO(null));// have to start with a valid BI + final BranchHandle bh = BranchHandle.getBranchHandle(new GOTO(null));// have to start with a valid BI Assert.assertNotNull(bh); bh.setInstruction(null); Assert.assertNotNull(bh); @@ -33,7 +33,7 @@ public class BranchHandleTestCase { @Test public void testsetInstructionBI() { - BranchHandle bh = BranchHandle.getBranchHandle(new GOTO(null));// have to start with a valid BI + final BranchHandle bh = BranchHandle.getBranchHandle(new GOTO(null));// have to start with a valid BI Assert.assertNotNull(bh); bh.setInstruction(new GOTO(null)); Assert.assertNotNull(bh); @@ -41,7 +41,7 @@ public class BranchHandleTestCase { @Test(expected=ClassGenException.class) public void testsetInstructionnotBI() { - BranchHandle bh = BranchHandle.getBranchHandle(new GOTO(null));// have to start with a valid BI + final BranchHandle bh = BranchHandle.getBranchHandle(new GOTO(null));// have to start with a valid BI Assert.assertNotNull(bh); bh.setInstruction(new NOP()); Assert.assertNotNull(bh); diff --git a/src/test/java/org/apache/bcel/generic/FieldAnnotationsTestCase.java b/src/test/java/org/apache/bcel/generic/FieldAnnotationsTestCase.java index f35369e4..41473c5a 100644 --- a/src/test/java/org/apache/bcel/generic/FieldAnnotationsTestCase.java +++ b/src/test/java/org/apache/bcel/generic/FieldAnnotationsTestCase.java @@ -35,7 +35,7 @@ public class FieldAnnotationsTestCase extends AbstractTestCase */ public void testFieldAnnotationEntrys() throws ClassNotFoundException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedFields"); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedFields"); // TODO L...;? checkAnnotatedField(clazz, "i", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "1"); checkAnnotatedField(clazz, "s", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "2"); @@ -47,13 +47,13 @@ public class FieldAnnotationsTestCase extends AbstractTestCase public void testFieldAnnotationEntrysReadWrite() throws ClassNotFoundException, IOException { - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedFields"); + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedFields"); checkAnnotatedField(clazz, "i", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "1"); checkAnnotatedField(clazz, "s", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "2"); // Write it out - File tfile = createTestdataFile("AnnotatedFields.class"); + final File tfile = createTestdataFile("AnnotatedFields.class"); clazz.dump(tfile); - SyntheticRepository repos2 = createRepos("."); + final SyntheticRepository repos2 = createRepos("."); repos2.loadClass("AnnotatedFields"); checkAnnotatedField(clazz, "i", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "1"); checkAnnotatedField(clazz, "s", "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;", "id", "2"); @@ -67,9 +67,9 @@ public class FieldAnnotationsTestCase extends AbstractTestCase public void testFieldAnnotationModification() throws ClassNotFoundException { - boolean dbg = false; - JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedFields"); - ClassGen clg = new ClassGen(clazz); + final boolean dbg = false; + final JavaClass clazz = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedFields"); + final ClassGen clg = new ClassGen(clazz); Field f = clg.getFields()[0]; if (dbg) { System.err.println("Field in freshly constructed class is: " + f); @@ -78,9 +78,9 @@ public class FieldAnnotationsTestCase extends AbstractTestCase System.err.println("AnnotationEntrys on field are: " + dumpAnnotationEntries(f.getAnnotationEntries())); } - AnnotationEntryGen fruitBasedAnnotationEntry = createFruitAnnotationEntry(clg + final AnnotationEntryGen fruitBasedAnnotationEntry = createFruitAnnotationEntry(clg .getConstantPool(), "Tomato", false); - FieldGen fg = new FieldGen(f, clg.getConstantPool()); + final FieldGen fg = new FieldGen(f, clg.getConstantPool()); if (dbg) { System.err.println("Adding AnnotationEntry to the field"); } @@ -117,9 +117,9 @@ public class FieldAnnotationsTestCase extends AbstractTestCase final String AnnotationEntryName, final String AnnotationEntryElementName, final String AnnotationEntryElementValue) { - Field[] fields = clazz.getFields(); - for (Field f : fields) { - AnnotationEntry[] fieldAnnotationEntrys = f.getAnnotationEntries(); + final Field[] fields = clazz.getFields(); + for (final Field f : fields) { + final AnnotationEntry[] fieldAnnotationEntrys = f.getAnnotationEntries(); if (f.getName().equals(fieldname)) { checkAnnotationEntry(fieldAnnotationEntrys[0], AnnotationEntryName, @@ -136,7 +136,7 @@ public class FieldAnnotationsTestCase extends AbstractTestCase .equals(name)); assertTrue("Expected AnnotationEntry to have one element but it had " + a.getElementValuePairs().length, a.getElementValuePairs().length == 1); - ElementValuePair envp = a.getElementValuePairs()[0]; + final ElementValuePair envp = a.getElementValuePairs()[0]; assertTrue("Expected element name " + elementname + " but was " + envp.getNameString(), elementname .equals(envp.getNameString())); @@ -150,7 +150,7 @@ public class FieldAnnotationsTestCase extends AbstractTestCase { for (int i = 0; i < a.getElementValuePairs().length; i++) { - ElementValuePair element = a.getElementValuePairs()[i]; + final ElementValuePair element = a.getElementValuePairs()[i]; if (element.getNameString().equals(name)) { if (!element.getValue().stringifyValue().equals(tostring)) diff --git a/src/test/java/org/apache/bcel/generic/GeneratingAnnotatedClassesTestCase.java b/src/test/java/org/apache/bcel/generic/GeneratingAnnotatedClassesTestCase.java index 324f67c0..95c4d8b1 100644 --- a/src/test/java/org/apache/bcel/generic/GeneratingAnnotatedClassesTestCase.java +++ b/src/test/java/org/apache/bcel/generic/GeneratingAnnotatedClassesTestCase.java @@ -73,18 +73,18 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase throws ClassNotFoundException { // Create HelloWorld - ClassGen cg = createClassGen("HelloWorld"); + final ClassGen cg = createClassGen("HelloWorld"); cg.setMajor(49); cg.setMinor(0); - ConstantPoolGen cp = cg.getConstantPool(); - InstructionList il = new InstructionList(); + final ConstantPoolGen cp = cg.getConstantPool(); + final InstructionList il = new InstructionList(); cg.addAnnotationEntry(createSimpleVisibleAnnotation(cp)); cg.addAnnotationEntry(createSimpleInvisibleAnnotation(cp)); buildClassContents(cg, cp, il); //System.out.println(cg.getJavaClass().toString()); dumpClass(cg, "HelloWorld.class"); - JavaClass jc = getClassFrom(".", "HelloWorld"); - AnnotationEntry[] as = jc.getAnnotationEntries(); + final JavaClass jc = getClassFrom(".", "HelloWorld"); + final AnnotationEntry[] as = jc.getAnnotationEntries(); assertTrue("Should be two AnnotationEntries but found " + as.length, as.length == 2); // TODO L??; @@ -96,12 +96,12 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase "Name of annotation 2 should be LSimpleAnnotation; but it is " + as[1].getAnnotationType(), as[1].getAnnotationType() .equals("LSimpleAnnotation;")); - ElementValuePair[] vals = as[0].getElementValuePairs(); - ElementValuePair nvp = vals[0]; + final ElementValuePair[] vals = as[0].getElementValuePairs(); + final ElementValuePair nvp = vals[0]; assertTrue( "Name of element in SimpleAnnotation should be 'id' but it is " + nvp.getNameString(), nvp.getNameString().equals("id")); - ElementValue ev = nvp.getValue(); + final ElementValue ev = nvp.getValue(); assertTrue("Type of element value should be int but it is " + ev.getElementValueType(), ev.getElementValueType() == ElementValue.PRIMITIVE_INT); @@ -118,9 +118,9 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase throws ClassNotFoundException { // Create HelloWorld - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - InstructionList il = new InstructionList(); + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final InstructionList il = new InstructionList(); buildClassContentsWithAnnotatedMethods(cg, cp, il); // Check annotation is OK int i = cg.getMethods()[0].getAnnotationEntries().length; @@ -128,18 +128,18 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase "Prior to dumping, main method should have 1 annotation but has " + i, i == 1); dumpClass(cg, "temp1" + File.separator + "HelloWorld.class"); - JavaClass jc2 = getClassFrom("temp1", "HelloWorld"); + final JavaClass jc2 = getClassFrom("temp1", "HelloWorld"); // Check annotation is OK i = jc2.getMethods()[0].getAnnotationEntries().length; assertTrue("JavaClass should say 1 annotation on main method but says " + i, i == 1); - ClassGen cg2 = new ClassGen(jc2); + final ClassGen cg2 = new ClassGen(jc2); // Check it now it is a ClassGen - Method[] m = cg2.getMethods(); + final Method[] m = cg2.getMethods(); i = m[0].getAnnotationEntries().length; assertTrue("The main 'Method' should have one annotation but has " + i, i == 1); - MethodGen mg = new MethodGen(m[0], cg2.getClassName(), cg2 + final MethodGen mg = new MethodGen(m[0], cg2.getClassName(), cg2 .getConstantPool()); // Check it finally when the Method is changed to a MethodGen i = mg.getAnnotationEntries().length; @@ -158,19 +158,19 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase throws ClassNotFoundException { // Create HelloWorld - ClassGen cg = createClassGen("HelloWorld"); - ConstantPoolGen cp = cg.getConstantPool(); - InstructionList il = new InstructionList(); + final ClassGen cg = createClassGen("HelloWorld"); + final ConstantPoolGen cp = cg.getConstantPool(); + final InstructionList il = new InstructionList(); buildClassContentsWithAnnotatedMethods(cg, cp, il); dumpClass(cg, "temp2", "HelloWorld.class"); - JavaClass jc2 = getClassFrom("temp2", "HelloWorld"); - ClassGen cg2 = new ClassGen(jc2); + final JavaClass jc2 = getClassFrom("temp2", "HelloWorld"); + final ClassGen cg2 = new ClassGen(jc2); // Main method after reading the class back in - Method mainMethod1 = jc2.getMethods()[0]; + final Method mainMethod1 = jc2.getMethods()[0]; assertTrue("The 'Method' should have one annotations but has " + mainMethod1.getAnnotationEntries().length, mainMethod1 .getAnnotationEntries().length == 1); - MethodGen mainMethod2 = new MethodGen(mainMethod1, cg2.getClassName(), + final MethodGen mainMethod2 = new MethodGen(mainMethod1, cg2.getClassName(), cg2.getConstantPool()); assertTrue("The 'MethodGen' should have one annotations but has " + mainMethod2.getAnnotationEntries().length, mainMethod2 @@ -180,10 +180,10 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase cg2.removeMethod(mainMethod1); cg2.addMethod(mainMethod2.getMethod()); dumpClass(cg2, "temp3", "HelloWorld.class"); - JavaClass jc3 = getClassFrom("temp3", "HelloWorld"); - ClassGen cg3 = new ClassGen(jc3); - Method mainMethod3 = cg3.getMethods()[1]; - int i = mainMethod3.getAnnotationEntries().length; + final JavaClass jc3 = getClassFrom("temp3", "HelloWorld"); + final ClassGen cg3 = new ClassGen(jc3); + final Method mainMethod3 = cg3.getMethods()[1]; + final int i = mainMethod3.getAnnotationEntries().length; assertTrue("The 'Method' should now have two annotations but has " + i, i == 2); assertTrue(wipe("temp2", "HelloWorld.class")); @@ -197,10 +197,10 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase public void testTransformClassToClassGen_SimpleTypes() throws ClassNotFoundException { - JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotatedClass"); - ClassGen cgen = new ClassGen(jc); + final JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotatedClass"); + final ClassGen cgen = new ClassGen(jc); // Check annotations are correctly preserved - AnnotationEntryGen[] annotations = cgen.getAnnotationEntries(); + final AnnotationEntryGen[] annotations = cgen.getAnnotationEntries(); assertTrue("Expected one annotation but found " + annotations.length, annotations.length == 1); } @@ -212,10 +212,10 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase public void testTransformClassToClassGen_EnumType() throws ClassNotFoundException { - JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedWithEnumClass"); - ClassGen cgen = new ClassGen(jc); + final JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedWithEnumClass"); + final ClassGen cgen = new ClassGen(jc); // Check annotations are correctly preserved - AnnotationEntryGen[] annotations = cgen.getAnnotationEntries(); + final AnnotationEntryGen[] annotations = cgen.getAnnotationEntries(); assertTrue("Expected one annotation but found " + annotations.length, annotations.length == 1); } @@ -227,40 +227,40 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase public void testTransformClassToClassGen_ArrayAndAnnotationTypes() throws ClassNotFoundException { - JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedWithCombinedAnnotation"); - ClassGen cgen = new ClassGen(jc); + final JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedWithCombinedAnnotation"); + final ClassGen cgen = new ClassGen(jc); // Check annotations are correctly preserved - AnnotationEntryGen[] annotations = cgen.getAnnotationEntries(); + final AnnotationEntryGen[] annotations = cgen.getAnnotationEntries(); assertTrue("Expected one annotation but found " + annotations.length, annotations.length == 1); - AnnotationEntryGen a = annotations[0]; + final AnnotationEntryGen a = annotations[0]; assertTrue("That annotation should only have one value but has " + a.getValues().size(), a.getValues().size() == 1); - ElementValuePairGen nvp = a.getValues().get(0); - ElementValueGen value = nvp.getValue(); + final ElementValuePairGen nvp = a.getValues().get(0); + final ElementValueGen value = nvp.getValue(); assertTrue("Value should be ArrayElementValueGen but is " + value, value instanceof ArrayElementValueGen); - ArrayElementValueGen arrayValue = (ArrayElementValueGen) value; + final ArrayElementValueGen arrayValue = (ArrayElementValueGen) value; assertTrue("Array value should be size one but is " + arrayValue.getElementValuesSize(), arrayValue .getElementValuesSize() == 1); - ElementValueGen innerValue = arrayValue.getElementValues().get(0); + final ElementValueGen innerValue = arrayValue.getElementValues().get(0); assertTrue( "Value in the array should be AnnotationElementValueGen but is " + innerValue, innerValue instanceof AnnotationElementValueGen); - AnnotationElementValueGen innerAnnotationValue = (AnnotationElementValueGen) innerValue; + final AnnotationElementValueGen innerAnnotationValue = (AnnotationElementValueGen) innerValue; assertTrue("Should be called L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation; but is called: " + innerAnnotationValue.getAnnotation().getTypeName(), innerAnnotationValue.getAnnotation().getTypeSignature().equals( "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;")); // check the three methods - Method[] methods = cgen.getMethods(); + final Method[] methods = cgen.getMethods(); assertEquals(3, methods.length); - for (Method method : methods) + for (final Method method : methods) { - String methodName= method.getName(); + final String methodName= method.getName(); if(methodName.equals("<init>")) { assertMethodAnnotations(method, 0, 1); @@ -283,8 +283,8 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase private void assertMethodAnnotations(final Method method, final int expectedNumberAnnotations, final int nExpectedArrayValues) { - String methodName= method.getName(); - AnnotationEntry[] annos= method.getAnnotationEntries(); + final String methodName= method.getName(); + final AnnotationEntry[] annos= method.getAnnotationEntries(); assertEquals("For "+methodName, expectedNumberAnnotations, annos.length); if(expectedNumberAnnotations!=0) { @@ -294,24 +294,24 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase private void assertArrayElementValue(final int nExpectedArrayValues, final AnnotationEntry anno) { - ElementValuePair elementValuePair = anno.getElementValuePairs()[0]; + final ElementValuePair elementValuePair = anno.getElementValuePairs()[0]; assertEquals("value", elementValuePair.getNameString()); - ArrayElementValue ev = (ArrayElementValue) elementValuePair.getValue(); - ElementValue[] eva = ev.getElementValuesArray(); + final ArrayElementValue ev = (ArrayElementValue) elementValuePair.getValue(); + final ElementValue[] eva = ev.getElementValuesArray(); assertEquals(nExpectedArrayValues, eva.length); } private void assertParameterAnnotations(final Method method, final int... expectedNumberOfParmeterAnnotations) { - String methodName= "For "+method.getName(); - ParameterAnnotationEntry[] parameterAnnotations= method.getParameterAnnotationEntries(); + final String methodName= "For "+method.getName(); + final ParameterAnnotationEntry[] parameterAnnotations= method.getParameterAnnotationEntries(); assertEquals(methodName, expectedNumberOfParmeterAnnotations.length, parameterAnnotations.length); int i= 0; - for (ParameterAnnotationEntry parameterAnnotation : parameterAnnotations) + for (final ParameterAnnotationEntry parameterAnnotation : parameterAnnotations) { - AnnotationEntry[] annos= parameterAnnotation.getAnnotationEntries(); - int expectedLength = expectedNumberOfParmeterAnnotations[i++]; + final AnnotationEntry[] annos= parameterAnnotation.getAnnotationEntries(); + final int expectedLength = expectedNumberOfParmeterAnnotations[i++]; assertEquals(methodName+" parameter "+i, expectedLength, annos.length); if(expectedLength!=0) { @@ -322,9 +322,9 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase private void assertSimpleElementValue(final AnnotationEntry anno) { - ElementValuePair elementValuePair = anno.getElementValuePairs()[0]; + final ElementValuePair elementValuePair = anno.getElementValuePairs()[0]; assertEquals("id", elementValuePair.getNameString()); - SimpleElementValue ev = (SimpleElementValue)elementValuePair.getValue(); + final SimpleElementValue ev = (SimpleElementValue)elementValuePair.getValue(); assertEquals(42, ev.getValueInt()); } @@ -334,16 +334,16 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase public void testTransformComplexClassToClassGen() throws ClassNotFoundException { - JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.ComplexAnnotatedClass"); - ClassGen cgen = new ClassGen(jc); + final JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.ComplexAnnotatedClass"); + final ClassGen cgen = new ClassGen(jc); // Check annotations are correctly preserved - AnnotationEntryGen[] annotations = cgen.getAnnotationEntries(); + final AnnotationEntryGen[] annotations = cgen.getAnnotationEntries(); assertTrue("Expected one annotation but found " + annotations.length, annotations.length == 1); - List<?> l = annotations[0].getValues(); + final List<?> l = annotations[0].getValues(); boolean found = false; - for (Object name : l) { - ElementValuePairGen element = (ElementValuePairGen) name; + for (final Object name : l) { + final ElementValuePairGen element = (ElementValuePairGen) name; if (element.getNameString().equals("dval")) { if (((SimpleElementValueGen) element.getValue()) @@ -362,9 +362,9 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase */ public void testModifyingClasses1() throws ClassNotFoundException { - JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotatedClass"); - ClassGen cgen = new ClassGen(jc); - ConstantPoolGen cp = cgen.getConstantPool(); + final JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotatedClass"); + final ClassGen cgen = new ClassGen(jc); + final ConstantPoolGen cp = cgen.getConstantPool(); cgen.addAnnotationEntry(createFruitAnnotation(cp, "Pineapple")); assertTrue("Should now have two annotations but has " + cgen.getAnnotationEntries().length, cgen @@ -379,15 +379,15 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase */ public void testModifyingClasses2() throws ClassNotFoundException { - JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotatedClass"); - ClassGen cgen = new ClassGen(jc); - ConstantPoolGen cp = cgen.getConstantPool(); + final JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.SimpleAnnotatedClass"); + final ClassGen cgen = new ClassGen(jc); + final ConstantPoolGen cp = cgen.getConstantPool(); cgen.addAnnotationEntry(createCombinedAnnotation(cp)); assertTrue("Should now have two annotations but has " + cgen.getAnnotationEntries().length, cgen .getAnnotationEntries().length == 2); dumpClass(cgen, "SimpleAnnotatedClass.class"); - JavaClass jc2 = getClassFrom(".", "SimpleAnnotatedClass"); + final JavaClass jc2 = getClassFrom(".", "SimpleAnnotatedClass"); jc2.getAnnotationEntries(); assertTrue(wipe("SimpleAnnotatedClass.class")); // System.err.println(jc2.toString()); @@ -397,10 +397,10 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase { try { - File f = createTestdataFile(fname); + final File f = createTestdataFile(fname); cg.getJavaClass().dump(f); } - catch (java.io.IOException e) + catch (final java.io.IOException e) { System.err.println(e); } @@ -415,13 +415,13 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase final ConstantPoolGen cp, final InstructionList il) { // Create method 'public static void main(String[]argv)' - MethodGen mg = createMethodGen("main", il, cp); - InstructionFactory factory = new InstructionFactory(cg); + final MethodGen mg = createMethodGen("main", il, cp); + final InstructionFactory factory = new InstructionFactory(cg); mg.addAnnotationEntry(createSimpleVisibleAnnotation(mg .getConstantPool())); // We now define some often used types: - ObjectType i_stream = new ObjectType("java.io.InputStream"); - ObjectType p_stream = new ObjectType("java.io.PrintStream"); + final ObjectType i_stream = new ObjectType("java.io.InputStream"); + final ObjectType p_stream = new ObjectType("java.io.PrintStream"); // Create variables in and name : We call the constructors, i.e., // execute BufferedReader(InputStreamReader(System.in)) . The reference // to the BufferedReader object stays on top of the stack and is stored @@ -439,11 +439,11 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase Const.INVOKESPECIAL)); LocalVariableGen lg = mg.addLocalVariable("in", new ObjectType( "java.io.BufferedReader"), null, null); - int in = lg.getIndex(); + final int in = lg.getIndex(); lg.setStart(il.append(new ASTORE(in))); // "in" valid from here // Create local variable name and initialize it to null lg = mg.addLocalVariable("name", Type.STRING, null, null); - int name = lg.getIndex(); + final int name = lg.getIndex(); il.append(InstructionConst.ACONST_NULL); lg.setStart(il.append(new ASTORE(name))); // "name" valid from here // Create try-catch block: We remember the start of the block, read a @@ -457,24 +457,24 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase // il.append(new ALOAD(in)); // il.append(factory.createInvoke("java.io.BufferedReader", "readLine", // Type.STRING, Type.NO_ARGS, Constants.INVOKEVIRTUAL)); - InstructionHandle try_start = il.append(new PUSH(cp, "Andy")); + final InstructionHandle try_start = il.append(new PUSH(cp, "Andy")); il.append(new ASTORE(name)); // Upon normal execution we jump behind exception handler, the target // address is not known yet. - GOTO g = new GOTO(null); - InstructionHandle try_end = il.append(g); + final GOTO g = new GOTO(null); + final InstructionHandle try_end = il.append(g); // We add the exception handler which simply returns from the method. - LocalVariableGen var_ex = mg.addLocalVariable("ex", Type + final LocalVariableGen var_ex = mg.addLocalVariable("ex", Type .getType("Ljava.io.IOException;"), null, null); - int var_ex_slot = var_ex.getIndex(); - InstructionHandle handler = il.append(new ASTORE(var_ex_slot)); + final int var_ex_slot = var_ex.getIndex(); + final InstructionHandle handler = il.append(new ASTORE(var_ex_slot)); var_ex.setStart(handler); var_ex.setEnd(il.append(InstructionConst.RETURN)); mg.addExceptionHandler(try_start, try_end, handler, new ObjectType( "java.io.IOException")); // "Normal" code continues, now we can set the branch target of the GOTO // . - InstructionHandle ih = il.append(factory.createFieldAccess( + final InstructionHandle ih = il.append(factory.createFieldAccess( "java.lang.System", "out", p_stream, Const.GETSTATIC)); g.setTarget(ih); // Printing "Hello": String concatenation compiles to StringBuffer @@ -511,11 +511,11 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase final InstructionList il) { // Create method 'public static void main(String[]argv)' - MethodGen mg = createMethodGen("main", il, cp); - InstructionFactory factory = new InstructionFactory(cg); + final MethodGen mg = createMethodGen("main", il, cp); + final InstructionFactory factory = new InstructionFactory(cg); // We now define some often used types: - ObjectType i_stream = new ObjectType("java.io.InputStream"); - ObjectType p_stream = new ObjectType("java.io.PrintStream"); + final ObjectType i_stream = new ObjectType("java.io.InputStream"); + final ObjectType p_stream = new ObjectType("java.io.PrintStream"); // Create variables in and name : We call the constructors, i.e., // execute BufferedReader(InputStreamReader(System.in)) . The reference // to the BufferedReader object stays on top of the stack and is stored @@ -533,11 +533,11 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase Const.INVOKESPECIAL)); LocalVariableGen lg = mg.addLocalVariable("in", new ObjectType( "java.io.BufferedReader"), null, null); - int in = lg.getIndex(); + final int in = lg.getIndex(); lg.setStart(il.append(new ASTORE(in))); // "in" valid from here // Create local variable name and initialize it to null lg = mg.addLocalVariable("name", Type.STRING, null, null); - int name = lg.getIndex(); + final int name = lg.getIndex(); il.append(InstructionConst.ACONST_NULL); lg.setStart(il.append(new ASTORE(name))); // "name" valid from here // Create try-catch block: We remember the start of the block, read a @@ -551,24 +551,24 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase // il.append(new ALOAD(in)); // il.append(factory.createInvoke("java.io.BufferedReader", "readLine", // Type.STRING, Type.NO_ARGS, Constants.INVOKEVIRTUAL)); - InstructionHandle try_start = il.append(new PUSH(cp, "Andy")); + final InstructionHandle try_start = il.append(new PUSH(cp, "Andy")); il.append(new ASTORE(name)); // Upon normal execution we jump behind exception handler, the target // address is not known yet. - GOTO g = new GOTO(null); - InstructionHandle try_end = il.append(g); + final GOTO g = new GOTO(null); + final InstructionHandle try_end = il.append(g); // We add the exception handler which simply returns from the method. - LocalVariableGen var_ex = mg.addLocalVariable("ex", Type + final LocalVariableGen var_ex = mg.addLocalVariable("ex", Type .getType("Ljava.io.IOException;"), null, null); - int var_ex_slot = var_ex.getIndex(); - InstructionHandle handler = il.append(new ASTORE(var_ex_slot)); + final int var_ex_slot = var_ex.getIndex(); + final InstructionHandle handler = il.append(new ASTORE(var_ex_slot)); var_ex.setStart(handler); var_ex.setEnd(il.append(InstructionConst.RETURN)); mg.addExceptionHandler(try_start, try_end, handler, new ObjectType( "java.io.IOException")); // "Normal" code continues, now we can set the branch target of the GOTO // . - InstructionHandle ih = il.append(factory.createFieldAccess( + final InstructionHandle ih = il.append(factory.createFieldAccess( "java.lang.System", "out", p_stream, Const.GETSTATIC)); g.setTarget(ih); // Printing "Hello": String concatenation compiles to StringBuffer @@ -605,7 +605,7 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase throws ClassNotFoundException { // System.out.println(where); - SyntheticRepository repos = createRepos(where); + final SyntheticRepository repos = createRepos(where); return repos.loadClass(clazzname); } @@ -631,24 +631,24 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase public AnnotationEntryGen createSimpleVisibleAnnotation(final ConstantPoolGen cp) { - SimpleElementValueGen evg = new SimpleElementValueGen( + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_INT, cp, 4); - ElementValuePairGen nvGen = new ElementValuePairGen("id", evg, cp); - ObjectType t = new ObjectType("SimpleAnnotation"); - List<ElementValuePairGen> elements = new ArrayList<>(); + final ElementValuePairGen nvGen = new ElementValuePairGen("id", evg, cp); + final ObjectType t = new ObjectType("SimpleAnnotation"); + final List<ElementValuePairGen> elements = new ArrayList<>(); elements.add(nvGen); - AnnotationEntryGen a = new AnnotationEntryGen(t, elements, true, cp); + final AnnotationEntryGen a = new AnnotationEntryGen(t, elements, true, cp); return a; } public AnnotationEntryGen createFruitAnnotation(final ConstantPoolGen cp, final String aFruit) { - SimpleElementValueGen evg = new SimpleElementValueGen( + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.STRING, cp, aFruit); - ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp); - ObjectType t = new ObjectType("SimpleStringAnnotation"); - List<ElementValuePairGen> elements = new ArrayList<>(); + final ElementValuePairGen nvGen = new ElementValuePairGen("fruit", evg, cp); + final ObjectType t = new ObjectType("SimpleStringAnnotation"); + final List<ElementValuePairGen> elements = new ArrayList<>(); elements.add(nvGen); return new AnnotationEntryGen(t, elements, true, cp); } @@ -656,11 +656,11 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase public AnnotationEntryGen createCombinedAnnotation(final ConstantPoolGen cp) { // Create an annotation instance - AnnotationEntryGen a = createSimpleVisibleAnnotation(cp); - ArrayElementValueGen array = new ArrayElementValueGen(cp); + final AnnotationEntryGen a = createSimpleVisibleAnnotation(cp); + final ArrayElementValueGen array = new ArrayElementValueGen(cp); array.addElement(new AnnotationElementValueGen(a, cp)); - ElementValuePairGen nvp = new ElementValuePairGen("value", array, cp); - List<ElementValuePairGen> elements = new ArrayList<>(); + final ElementValuePairGen nvp = new ElementValuePairGen("value", array, cp); + final List<ElementValuePairGen> elements = new ArrayList<>(); elements.add(nvp); return new AnnotationEntryGen(new ObjectType("CombinedAnnotation"), elements, true, cp); @@ -668,13 +668,13 @@ public class GeneratingAnnotatedClassesTestCase extends AbstractTestCase public AnnotationEntryGen createSimpleInvisibleAnnotation(final ConstantPoolGen cp) { - SimpleElementValueGen evg = new SimpleElementValueGen( + final SimpleElementValueGen evg = new SimpleElementValueGen( ElementValueGen.PRIMITIVE_INT, cp, 4); - ElementValuePairGen nvGen = new ElementValuePairGen("id", evg, cp); - ObjectType t = new ObjectType("SimpleAnnotation"); - List<ElementValuePairGen> elements = new ArrayList<>(); + final ElementValuePairGen nvGen = new ElementValuePairGen("id", evg, cp); + final ObjectType t = new ObjectType("SimpleAnnotation"); + final List<ElementValuePairGen> elements = new ArrayList<>(); elements.add(nvGen); - AnnotationEntryGen a = new AnnotationEntryGen(t, elements, false, cp); + final AnnotationEntryGen a = new AnnotationEntryGen(t, elements, false, cp); return a; } } diff --git a/src/test/java/org/apache/bcel/generic/InstructionHandleTestCase.java b/src/test/java/org/apache/bcel/generic/InstructionHandleTestCase.java index 92c243fe..aefa8da1 100644 --- a/src/test/java/org/apache/bcel/generic/InstructionHandleTestCase.java +++ b/src/test/java/org/apache/bcel/generic/InstructionHandleTestCase.java @@ -26,7 +26,7 @@ public class InstructionHandleTestCase { @Test(expected=ClassGenException.class) public void testsetInstructionNull() { - InstructionHandle ih = InstructionHandle.getInstructionHandle(new NOP());// have to start with a valid non BI + final InstructionHandle ih = InstructionHandle.getInstructionHandle(new NOP());// have to start with a valid non BI Assert.assertNotNull(ih); ih.setInstruction(null); Assert.assertNotNull(ih); @@ -34,7 +34,7 @@ public class InstructionHandleTestCase { @Test public void testsetInstructionI() { - InstructionHandle ih = InstructionHandle.getInstructionHandle(new NOP());// have to start with a valid non BI + final InstructionHandle ih = InstructionHandle.getInstructionHandle(new NOP());// have to start with a valid non BI Assert.assertNotNull(ih); ih.setInstruction(new NOP()); Assert.assertNotNull(ih); @@ -42,7 +42,7 @@ public class InstructionHandleTestCase { @Test(expected=ClassGenException.class) public void testsetInstructionnotI() { - InstructionHandle ih = InstructionHandle.getInstructionHandle(new NOP());// have to start with a valid non BI + final InstructionHandle ih = InstructionHandle.getInstructionHandle(new NOP());// have to start with a valid non BI Assert.assertNotNull(ih); ih.setInstruction(new GOTO(null)); Assert.assertNotNull(ih); @@ -55,8 +55,8 @@ public class InstructionHandleTestCase { @Test public void testBCEL195() { - InstructionList il = new InstructionList(); - InstructionHandle ih = il.append(InstructionConst.NOP); + final InstructionList il = new InstructionList(); + final InstructionHandle ih = il.append(InstructionConst.NOP); new TABLESWITCH(new int[0], new InstructionHandle[0], ih); new TABLESWITCH(new int[0], new InstructionHandle[0], ih); } diff --git a/src/test/java/org/apache/bcel/generic/JDKGenericDumpTestCase.java b/src/test/java/org/apache/bcel/generic/JDKGenericDumpTestCase.java index bf9f18f7..ac182f78 100644 --- a/src/test/java/org/apache/bcel/generic/JDKGenericDumpTestCase.java +++ b/src/test/java/org/apache/bcel/generic/JDKGenericDumpTestCase.java @@ -42,8 +42,8 @@ public class JDKGenericDumpTestCase { @Test public void testJDKjars() throws Exception { - File[] jars = listJDKjars(); - for (File file : jars) { + final File[] jars = listJDKjars(); + for (final File file : jars) { testJar(file); } } @@ -51,16 +51,16 @@ public class JDKGenericDumpTestCase { private void testJar(final File file) throws Exception { System.out.println(file); try (JarFile jar = new JarFile(file)) { - Enumeration<JarEntry> en = jar.entries(); + final Enumeration<JarEntry> en = jar.entries(); while (en.hasMoreElements()) { - JarEntry e = en.nextElement(); + final JarEntry e = en.nextElement(); final String name = e.getName(); if (name.endsWith(".class")) { // System.out.println("- " + name); try (InputStream in = jar.getInputStream(e)) { - ClassParser parser = new ClassParser(in, name); - JavaClass jc = parser.parse(); - for (Method m : jc.getMethods()) { + final ClassParser parser = new ClassParser(in, name); + final JavaClass jc = parser.parse(); + for (final Method m : jc.getMethods()) { compare(name, m); } } @@ -71,20 +71,20 @@ public class JDKGenericDumpTestCase { private void compare(final String name, final Method m) { // System.out.println("Method: " + m); - Code c = m.getCode(); + final Code c = m.getCode(); if (c==null) { return; // e.g. abstract method } - byte[] src = c.getCode(); - InstructionList il = new InstructionList(src); - byte[] out = il.getByteCode(); + final byte[] src = c.getCode(); + final InstructionList il = new InstructionList(src); + final byte[] out = il.getByteCode(); if (src.length == out.length) { assertArrayEquals(name + ": "+m.toString(), src, out); } else { System.out.println(name + ": "+m.toString() +" "+ src.length+" "+out.length); System.out.println(bytesToHex(src)); System.out.println(bytesToHex(out)); - for (InstructionHandle ih : il) { + for (final InstructionHandle ih : il) { System.out.println(ih.toString(false)); } fail("Array comparison failure"); @@ -92,7 +92,7 @@ public class JDKGenericDumpTestCase { } private File[] listJDKjars() throws Exception { - File javaLib = new File(System.getProperty("java.home") + "/lib"); + final File javaLib = new File(System.getProperty("java.home") + "/lib"); return javaLib.listFiles(new FileFilter() { @Override public boolean accept(final File file) { @@ -103,10 +103,10 @@ public class JDKGenericDumpTestCase { private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); private static String bytesToHex(final byte[] bytes) { - char[] hexChars = new char[bytes.length * 3]; + final char[] hexChars = new char[bytes.length * 3]; int i=0; - for (byte b : bytes) { - int v = b & 0xFF; + for (final byte b : bytes) { + final int v = b & 0xFF; hexChars[i++] = hexArray[v >>> 4]; hexChars[i++] = hexArray[v & 0x0F]; hexChars[i++] = ' '; diff --git a/src/test/java/org/apache/bcel/generic/MethodGenTestCase.java b/src/test/java/org/apache/bcel/generic/MethodGenTestCase.java index 859b34bc..4f080999 100644 --- a/src/test/java/org/apache/bcel/generic/MethodGenTestCase.java +++ b/src/test/java/org/apache/bcel/generic/MethodGenTestCase.java @@ -30,14 +30,15 @@ public class MethodGenTestCase extends TestCase { public static class Foo { public void bar() { @SuppressWarnings("unused") + final int a = 1; } } private MethodGen getMethod(final Class<?> cls, final String name) throws ClassNotFoundException { - JavaClass jc = Repository.lookupClass(cls); - ConstantPoolGen cp = new ConstantPoolGen(jc.getConstantPool()); - for (Method method : jc.getMethods()) { + final JavaClass jc = Repository.lookupClass(cls); + final ConstantPoolGen cp = new ConstantPoolGen(jc.getConstantPool()); + for (final Method method : jc.getMethods()) { if (method.getName().equals(name)) { return new MethodGen(method, jc.getClassName(), cp); } @@ -48,12 +49,12 @@ public class MethodGenTestCase extends TestCase { } public void testRemoveLocalVariable() throws Exception { - MethodGen mg = getMethod(Foo.class, "bar"); + final MethodGen mg = getMethod(Foo.class, "bar"); - LocalVariableGen lv = mg.getLocalVariables()[1]; + final LocalVariableGen lv = mg.getLocalVariables()[1]; assertEquals("variable name", "a", lv.getName()); - InstructionHandle start = lv.getStart(); - InstructionHandle end = lv.getEnd(); + final InstructionHandle start = lv.getStart(); + final InstructionHandle end = lv.getEnd(); assertNotNull("scope start", start); assertNotNull("scope end", end); assertTrue("scope start not targeted by the local variable", Arrays.asList(start.getTargeters()).contains(lv)); @@ -69,12 +70,12 @@ public class MethodGenTestCase extends TestCase { } public void testRemoveLocalVariables() throws Exception { - MethodGen mg = getMethod(Foo.class, "bar"); + final MethodGen mg = getMethod(Foo.class, "bar"); - LocalVariableGen lv = mg.getLocalVariables()[1]; + final LocalVariableGen lv = mg.getLocalVariables()[1]; assertEquals("variable name", "a", lv.getName()); - InstructionHandle start = lv.getStart(); - InstructionHandle end = lv.getEnd(); + final InstructionHandle start = lv.getStart(); + final InstructionHandle end = lv.getEnd(); assertNotNull("scope start", start); assertNotNull("scope end", end); assertTrue("scope start not targeted by the local variable", Arrays.asList(start.getTargeters()).contains(lv)); diff --git a/src/test/java/org/apache/bcel/generic/TypeTestCase.java b/src/test/java/org/apache/bcel/generic/TypeTestCase.java index 7b00d8b4..5b5e6f5b 100644 --- a/src/test/java/org/apache/bcel/generic/TypeTestCase.java +++ b/src/test/java/org/apache/bcel/generic/TypeTestCase.java @@ -25,8 +25,8 @@ public class TypeTestCase extends TestCase { // The line commented out above is the correct expected value; however, // the constructor for ObjectType is yet another place where BCEL does // not understand generics so we need to substitute the modified value below. - String expectedValue = "Ljava/util/Map<X, java/util/List<Y>>;"; - String actualValue = (Type.getType("Ljava/util/Map<TX;Ljava/util/List<TY;>;>;")).getSignature(); + final String expectedValue = "Ljava/util/Map<X, java/util/List<Y>>;"; + final String actualValue = (Type.getType("Ljava/util/Map<TX;Ljava/util/List<TY;>;>;")).getSignature(); assertEquals("Type.getType", expectedValue, actualValue); } diff --git a/src/test/java/org/apache/bcel/util/BCELifierTestCase.java b/src/test/java/org/apache/bcel/util/BCELifierTestCase.java index a2ebba47..c383798d 100644 --- a/src/test/java/org/apache/bcel/util/BCELifierTestCase.java +++ b/src/test/java/org/apache/bcel/util/BCELifierTestCase.java @@ -33,10 +33,10 @@ public class BCELifierTestCase { @Test public void test() throws Exception { - OutputStream os = new ByteArrayOutputStream(); - JavaClass java_class = BCELifier.getJavaClass("Java8Example"); + final OutputStream os = new ByteArrayOutputStream(); + final JavaClass java_class = BCELifier.getJavaClass("Java8Example"); assertNotNull(java_class); - BCELifier bcelifier = new BCELifier(java_class, os); + final BCELifier bcelifier = new BCELifier(java_class, os); bcelifier.start(); } @@ -55,12 +55,12 @@ public class BCELifierTestCase { final String initial = exec(null, "javap", "-p", "-c", javaClass); final File workDir = new File("target"); - File infile = new File(javaClass); - JavaClass java_class = BCELifier.getJavaClass(infile.getName().replace(".class", "")); + final File infile = new File(javaClass); + final JavaClass java_class = BCELifier.getJavaClass(infile.getName().replace(".class", "")); assertNotNull(java_class); - File outfile = new File(workDir, infile.getName().replace(".class", "Creator.java")); + final File outfile = new File(workDir, infile.getName().replace(".class", "Creator.java")); try (FileOutputStream fos = new FileOutputStream(outfile)) { - BCELifier bcelifier = new BCELifier(java_class, fos); + final BCELifier bcelifier = new BCELifier(java_class, fos); bcelifier.start(); } exec(workDir, "javac", "-cp", "classes", outfile.getName()); @@ -79,19 +79,19 @@ public class BCELifierTestCase { private String exec(final File workDir, final String... args) throws Exception { // System.err.println(java.util.Arrays.toString(args)); - ProcessBuilder pb = new ProcessBuilder(args); + final ProcessBuilder pb = new ProcessBuilder(args); pb.directory(workDir); - Process proc = pb.start(); + final Process proc = pb.start(); try (BufferedInputStream is = new BufferedInputStream(proc.getInputStream()); InputStream es = proc.getErrorStream()) { proc.waitFor(); - byte[] buff = new byte[2048]; + final byte[] buff = new byte[2048]; int len; while ((len = es.read(buff)) != -1) { System.err.print(new String(buff, 0, len)); } - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); while ((len = is.read(buff)) != -1) { sb.append(new String(buff, 0, len)); } diff --git a/src/test/java/org/apache/bcel/util/Class2HTMLTestCase.java b/src/test/java/org/apache/bcel/util/Class2HTMLTestCase.java index 42113f77..ca455b18 100644 --- a/src/test/java/org/apache/bcel/util/Class2HTMLTestCase.java +++ b/src/test/java/org/apache/bcel/util/Class2HTMLTestCase.java @@ -28,14 +28,14 @@ import junit.framework.TestCase; public class Class2HTMLTestCase extends TestCase { public void testConvertJavaUtil() throws Exception { - File outputDir = new File("target/test-output/html"); + final File outputDir = new File("target/test-output/html"); if (!outputDir.mkdirs()) { // either was not created or already existed Assert.assertTrue(outputDir.isDirectory()); // fail if missing } try (FileInputStream file = new FileInputStream("target/test-classes/Java8Example.class")) { - ClassParser parser = new ClassParser(file, "Java8Example.class"); + final ClassParser parser = new ClassParser(file, "Java8Example.class"); new Class2HTML(parser.parse(), outputDir.getAbsolutePath() + "/"); } diff --git a/src/test/java/org/apache/bcel/util/InstructionFinderTest.java b/src/test/java/org/apache/bcel/util/InstructionFinderTest.java index 76e771b9..2a506937 100644 --- a/src/test/java/org/apache/bcel/util/InstructionFinderTest.java +++ b/src/test/java/org/apache/bcel/util/InstructionFinderTest.java @@ -30,15 +30,15 @@ import org.apache.bcel.generic.InstructionList; public class InstructionFinderTest extends AbstractTestCase { public void testSearch() { - InstructionList il = new InstructionList(); + final InstructionList il = new InstructionList(); il.append(new ILOAD(1)); il.append(new ILOAD(2)); il.append(new IADD()); il.append(new ISTORE(3)); - InstructionFinder finder = new InstructionFinder(il); + final InstructionFinder finder = new InstructionFinder(il); - Iterator<?> it = finder.search("ILOAD IADD", il.getInstructionHandles()[0], null ); - InstructionHandle[] ihs = (InstructionHandle[])it.next(); + final Iterator<?> it = finder.search("ILOAD IADD", il.getInstructionHandles()[0], null ); + final InstructionHandle[] ihs = (InstructionHandle[])it.next(); assertEquals(2, ihs.length); assertEquals(ihs[0].getInstruction(), new ILOAD(2)); assertEquals(ihs[1].getInstruction(), new IADD()); diff --git a/src/test/java/org/apache/bcel/verifier/AbstractVerifierTestCase.java b/src/test/java/org/apache/bcel/verifier/AbstractVerifierTestCase.java index bba0d4d8..e691e84c 100644 --- a/src/test/java/org/apache/bcel/verifier/AbstractVerifierTestCase.java +++ b/src/test/java/org/apache/bcel/verifier/AbstractVerifierTestCase.java @@ -60,14 +60,14 @@ public abstract class AbstractVerifierTestCase extends TestCase { int nbMethods = 0; try { - JavaClass jc = Repository.lookupClass(classname); + final JavaClass jc = Repository.lookupClass(classname); nbMethods = jc.getMethods().length; - } catch (ClassNotFoundException e) { + } catch (final ClassNotFoundException e) { fail(e.getMessage()); return false; } - Verifier verifier = VerifierFactory.getVerifier(classname); + final Verifier verifier = VerifierFactory.getVerifier(classname); VerificationResult result = verifier.doPass1(); if (result.getStatus() != VerificationResult.VERIFIED_OK) { return false; diff --git a/src/test/java/org/apache/bcel/verifier/VerifierTestCase.java b/src/test/java/org/apache/bcel/verifier/VerifierTestCase.java index 1e68bc4b..bf554df9 100644 --- a/src/test/java/org/apache/bcel/verifier/VerifierTestCase.java +++ b/src/test/java/org/apache/bcel/verifier/VerifierTestCase.java @@ -25,9 +25,9 @@ import junit.framework.TestCase; public class VerifierTestCase extends TestCase { public void testDefaultMethodValidation() { - String classname = Collection.class.getName(); + final String classname = Collection.class.getName(); - Verifier verifier = VerifierFactory.getVerifier(classname); + final Verifier verifier = VerifierFactory.getVerifier(classname); VerificationResult result = verifier.doPass1(); assertEquals("Pass 1 verification of " + classname + " failed: " + result.getMessage(), VerificationResult.VERIFIED_OK, diff --git a/src/test/java/org/apache/bcel/verifier/tests/TestArray01.java b/src/test/java/org/apache/bcel/verifier/tests/TestArray01.java index 0dc9fb43..3ead0d60 100644 --- a/src/test/java/org/apache/bcel/verifier/tests/TestArray01.java +++ b/src/test/java/org/apache/bcel/verifier/tests/TestArray01.java @@ -22,7 +22,7 @@ import java.io.Serializable; public class TestArray01{ public static Object test1() { - String[] a = new String[4]; + final String[] a = new String[4]; a[0] = ""; a.equals(null); test2(a); diff --git a/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess01.java b/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess01.java index 1b83eee2..efd421c5 100644 --- a/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess01.java +++ b/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess01.java @@ -21,7 +21,7 @@ package org.apache.bcel.verifier.tests; public class TestArrayAccess01 extends XTestArray01{ public static void test() { - XTestArray01[] array = new TestArrayAccess01[1]; + final XTestArray01[] array = new TestArrayAccess01[1]; array[0] = new XTestArray01(); } diff --git a/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess02Creator.java b/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess02Creator.java index 4e81b7d9..7054df8e 100644 --- a/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess02Creator.java +++ b/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess02Creator.java @@ -54,14 +54,14 @@ public void create(final OutputStream out) throws IOException { } private void createMethod_0() { - InstructionList il = new InstructionList(); - MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "<init>", + final InstructionList il = new InstructionList(); + final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "<init>", TEST_PACKAGE+".TestArrayAccess02", il, _cp); - InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); + final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); Assert.assertNotNull(ih_0); // TODO why is this not used il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL)); - InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID)); + final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID)); Assert.assertNotNull(ih_4); // TODO why is this not used method.setMaxStack(); method.setMaxLocals(); @@ -70,26 +70,26 @@ public void create(final OutputStream out) throws IOException { } private void createMethod_1() { - InstructionList il = new InstructionList(); - MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, Type.NO_ARGS, new String[] { }, + final InstructionList il = new InstructionList(); + final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, Type.NO_ARGS, new String[] { }, "test", TEST_PACKAGE+".TestArrayAccess02", il, _cp); - InstructionHandle ih_0 = il.append(new PUSH(_cp, 1)); + final InstructionHandle ih_0 = il.append(new PUSH(_cp, 1)); Assert.assertNotNull(ih_0); // TODO why is this not used il.append(_factory.createNewArray(new ObjectType(TEST_PACKAGE+".TestArrayAccess02"), (short) 1)); il.append(InstructionFactory.createStore(Type.OBJECT, 0)); - InstructionHandle ih_5 = il.append(new PUSH(_cp, 1)); + final InstructionHandle ih_5 = il.append(new PUSH(_cp, 1)); Assert.assertNotNull(ih_5); // TODO why is this not used il.append(_factory.createNewArray(Type.STRING, (short) 1)); il.append(InstructionFactory.createStore(Type.OBJECT, 1)); - InstructionHandle ih_10 = il.append(InstructionFactory.createLoad(Type.OBJECT, 1)); + final InstructionHandle ih_10 = il.append(InstructionFactory.createLoad(Type.OBJECT, 1)); Assert.assertNotNull(ih_10); // TODO why is this not used il.append(new PUSH(_cp, 0)); il.append(_factory.createNew(TEST_PACKAGE+".TestArrayAccess02")); il.append(InstructionConst.DUP); il.append(_factory.createInvoke(TEST_PACKAGE+".TestArrayAccess02", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL)); il.append(InstructionConst.AASTORE); - InstructionHandle ih_20 = il.append(InstructionFactory.createReturn(Type.VOID)); + final InstructionHandle ih_20 = il.append(InstructionFactory.createReturn(Type.VOID)); Assert.assertNotNull(ih_20); // TODO why is this not used method.setMaxStack(); method.setMaxLocals(); diff --git a/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess03Creator.java b/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess03Creator.java index 2a7ebce9..73db8893 100644 --- a/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess03Creator.java +++ b/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess03Creator.java @@ -54,14 +54,14 @@ public void create(final OutputStream out) throws IOException { } private void createMethod_0() { - InstructionList il = new InstructionList(); - MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "<init>", + final InstructionList il = new InstructionList(); + final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "<init>", TEST_PACKAGE+".TestArrayAccess03", il, _cp); - InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); + final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); Assert.assertNotNull(ih_0); // TODO why is this not used il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL)); - InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID)); + final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID)); Assert.assertNotNull(ih_4); // TODO why is this not used method.setMaxStack(); method.setMaxLocals(); @@ -70,22 +70,22 @@ public void create(final OutputStream out) throws IOException { } private void createMethod_1() { - InstructionList il = new InstructionList(); - MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, new Type[] { Type.OBJECT }, + final InstructionList il = new InstructionList(); + final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, new Type[] { Type.OBJECT }, new String[] { "arg0" }, "test", TEST_PACKAGE+".TestArrayAccess03", il, _cp); - InstructionHandle ih_0 = il.append(new PUSH(_cp, 1)); + final InstructionHandle ih_0 = il.append(new PUSH(_cp, 1)); Assert.assertNotNull(ih_0); // TODO why is this not used il.append(_factory.createNewArray(new ObjectType(TEST_PACKAGE+".TestArrayAccess03"), (short) 1)); il.append(InstructionFactory.createStore(Type.OBJECT, 1)); - InstructionHandle ih_5 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); + final InstructionHandle ih_5 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); Assert.assertNotNull(ih_5); // TODO why is this not used il.append(new PUSH(_cp, 0)); il.append(_factory.createNew(TEST_PACKAGE+".TestArrayAccess03")); il.append(InstructionConst.DUP); il.append(_factory.createInvoke(TEST_PACKAGE+".TestArrayAccess03", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL)); il.append(InstructionConst.AASTORE); - InstructionHandle ih_15 = il.append(InstructionFactory.createReturn(Type.VOID)); + final InstructionHandle ih_15 = il.append(InstructionFactory.createReturn(Type.VOID)); Assert.assertNotNull(ih_15); // TODO why is this not used method.setMaxStack(); method.setMaxLocals(); diff --git a/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess04Creator.java b/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess04Creator.java index 54709327..f0ef81ad 100644 --- a/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess04Creator.java +++ b/src/test/java/org/apache/bcel/verifier/tests/TestArrayAccess04Creator.java @@ -54,14 +54,14 @@ public void create(final OutputStream out) throws IOException { } private void createMethod_0() { - InstructionList il = new InstructionList(); - MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "<init>", + final InstructionList il = new InstructionList(); + final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "<init>", TEST_PACKAGE+".TestArrayAccess04", il, _cp); - InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); + final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); Assert.assertNotNull(ih_0); // TODO why is this not used il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL)); - InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID)); + final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID)); Assert.assertNotNull(ih_4); // TODO why is this not used method.setMaxStack(); method.setMaxLocals(); @@ -70,23 +70,23 @@ public void create(final OutputStream out) throws IOException { } private void createMethod_1() { - InstructionList il = new InstructionList(); - MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, new Type[] { Type.OBJECT }, + final InstructionList il = new InstructionList(); + final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, new Type[] { Type.OBJECT }, new String[] { "arg0" }, "test", TEST_PACKAGE+".TestArrayAccess04", il, _cp); - InstructionHandle ih_0 = il.append(new PUSH(_cp, 1)); + final InstructionHandle ih_0 = il.append(new PUSH(_cp, 1)); Assert.assertNotNull(ih_0); // TODO why is this not used il.append(_factory.createNewArray(Type.OBJECT, (short) 1)); il.append(InstructionFactory.createStore(Type.OBJECT, 1)); - InstructionHandle ih_5 = il.append(new PUSH(_cp, 1)); + final InstructionHandle ih_5 = il.append(new PUSH(_cp, 1)); Assert.assertNotNull(ih_5); // TODO why is this not used il.append(InstructionFactory.createStore(Type.INT, 2)); - InstructionHandle ih_7 = il.append(InstructionFactory.createLoad(Type.OBJECT, 1)); + final InstructionHandle ih_7 = il.append(InstructionFactory.createLoad(Type.OBJECT, 1)); Assert.assertNotNull(ih_7); // TODO why is this not used il.append(new PUSH(_cp, 0)); il.append(InstructionFactory.createLoad(Type.INT, 2)); il.append(InstructionConst.AASTORE); - InstructionHandle ih_11 = il.append(InstructionFactory.createReturn(Type.VOID)); + final InstructionHandle ih_11 = il.append(InstructionFactory.createReturn(Type.VOID)); Assert.assertNotNull(ih_11); // TODO why is this not used method.setMaxStack(); method.setMaxLocals(); diff --git a/src/test/java/org/apache/bcel/verifier/tests/TestCreator.java b/src/test/java/org/apache/bcel/verifier/tests/TestCreator.java index 929bc86f..159e65db 100644 --- a/src/test/java/org/apache/bcel/verifier/tests/TestCreator.java +++ b/src/test/java/org/apache/bcel/verifier/tests/TestCreator.java @@ -29,14 +29,14 @@ public abstract class TestCreator { protected static final String TEST_PACKAGE = TestCreator.class.getPackage().getName(); public void create() throws IOException { - File classFile = new File(getPackageFolder(), getClassName()); + final File classFile = new File(getPackageFolder(), getClassName()); try (FileOutputStream out = new FileOutputStream(classFile)) { create(out); } } private String getClassName() { - String name = getClass().getName(); + final String name = getClass().getName(); return name.substring(name.lastIndexOf('.')+1).replace("Creator", ".class"); } @@ -51,7 +51,7 @@ public abstract class TestCreator { private File getClassesFolder() throws IOException { try { return new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()); - } catch (URISyntaxException e) { + } catch (final URISyntaxException e) { throw new IOException(e); } } diff --git a/src/test/java/org/apache/bcel/verifier/tests/TestReturn01Creator.java b/src/test/java/org/apache/bcel/verifier/tests/TestReturn01Creator.java index 96843336..8ace1f41 100644 --- a/src/test/java/org/apache/bcel/verifier/tests/TestReturn01Creator.java +++ b/src/test/java/org/apache/bcel/verifier/tests/TestReturn01Creator.java @@ -52,14 +52,14 @@ public void create(final OutputStream out) throws IOException { } private void createMethod_0() { - InstructionList il = new InstructionList(); - MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, + final InstructionList il = new InstructionList(); + final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "<init>", TEST_PACKAGE+".TestReturn01", il, _cp); - InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); + final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); Assert.assertNotNull(ih_0); // TODO why is this not used il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL)); - InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID)); + final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID)); Assert.assertNotNull(ih_4); // TODO why is this not used method.setMaxStack(); method.setMaxLocals(); @@ -68,16 +68,16 @@ public void create(final OutputStream out) throws IOException { } private void createMethod_1() { - InstructionList il = new InstructionList(); - MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, Type.NO_ARGS, + final InstructionList il = new InstructionList(); + final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.VOID, Type.NO_ARGS, new String[] { }, "foo", TEST_PACKAGE+".TestReturn01", il, _cp); - InstructionHandle ih_0 = il.append(_factory.createNew("java.lang.Object")); + final InstructionHandle ih_0 = il.append(_factory.createNew("java.lang.Object")); Assert.assertNotNull(ih_0); // TODO why is this not used il.append(InstructionConst.DUP); il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL)); il.append(InstructionConst.NOP); - InstructionHandle ih_8 = il.append(InstructionFactory.createReturn(Type.OBJECT)); + final InstructionHandle ih_8 = il.append(InstructionFactory.createReturn(Type.OBJECT)); Assert.assertNotNull(ih_8); // TODO why is this not used method.setMaxStack(); method.setMaxLocals(); diff --git a/src/test/java/org/apache/bcel/verifier/tests/TestReturn03Creator.java b/src/test/java/org/apache/bcel/verifier/tests/TestReturn03Creator.java index bea20f27..9445ab7c 100644 --- a/src/test/java/org/apache/bcel/verifier/tests/TestReturn03Creator.java +++ b/src/test/java/org/apache/bcel/verifier/tests/TestReturn03Creator.java @@ -52,14 +52,14 @@ public void create(final OutputStream out) throws IOException { } private void createMethod_0() { - InstructionList il = new InstructionList(); - MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, + final InstructionList il = new InstructionList(); + final MethodGen method = new MethodGen(Const.ACC_PUBLIC, Type.VOID, Type.NO_ARGS, new String[] { }, "<init>", TEST_PACKAGE+".TestReturn03", il, _cp); - InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); + final InstructionHandle ih_0 = il.append(InstructionFactory.createLoad(Type.OBJECT, 0)); Assert.assertNotNull(ih_0); // TODO why is this not used il.append(_factory.createInvoke("java.lang.Object", "<init>", Type.VOID, Type.NO_ARGS, Const.INVOKESPECIAL)); - InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID)); + final InstructionHandle ih_4 = il.append(InstructionFactory.createReturn(Type.VOID)); Assert.assertNotNull(ih_4); // TODO why is this not used method.setMaxStack(); method.setMaxLocals(); @@ -68,11 +68,11 @@ public void create(final OutputStream out) throws IOException { } private void createMethod_1() { - InstructionList il = new InstructionList(); - MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.INT, Type.NO_ARGS, + final InstructionList il = new InstructionList(); + final MethodGen method = new MethodGen(Const.ACC_PUBLIC | Const.ACC_STATIC, Type.INT, Type.NO_ARGS, new String[] { }, "test3", TEST_PACKAGE+".TestReturn03", il, _cp); - InstructionHandle ih_0 = il.append(InstructionConst.ACONST_NULL); + final InstructionHandle ih_0 = il.append(InstructionConst.ACONST_NULL); Assert.assertNotNull(ih_0); // TODO why is this not used il.append(InstructionFactory.createReturn(Type.OBJECT)); method.setMaxStack(); |