View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.bcel.classfile;
20  
21  import java.io.DataInput;
22  import java.io.IOException;
23  import java.util.Objects;
24  
25  import org.apache.bcel.generic.Type;
26  import org.apache.bcel.util.BCELComparator;
27  
28  /**
29   * This class represents the method info structure, that is, the representation for a method in the class. See JVM
30   * specification for details. A method has access flags, a name, a signature and a number of attributes.
31   */
32  public final class Method extends FieldOrMethod {
33  
34      /**
35       * Empty array constant.
36       *
37       * @since 6.6.0
38       */
39      public static final Method[] EMPTY_ARRAY = {};
40  
41      private static BCELComparator<Method> bcelComparator = new BCELComparator<Method>() {
42  
43          @Override
44          public boolean equals(final Method a, final Method b) {
45              return a == b || a != null && b != null && Objects.equals(a.getName(), b.getName()) && Objects.equals(a.getSignature(), b.getSignature());
46          }
47  
48          @Override
49          public int hashCode(final Method o) {
50              return o != null ? Objects.hash(o.getSignature(), o.getName()) : 0;
51          }
52      };
53  
54      /**
55       * Gets the comparison strategy object.
56       *
57       * @return Comparison strategy object.
58       */
59      public static BCELComparator<Method> getComparator() {
60          return bcelComparator;
61      }
62  
63      /**
64       * Sets the comparison strategy object.
65       *
66       * @param comparator Comparison strategy object.
67       */
68      public static void setComparator(final BCELComparator<Method> comparator) {
69          bcelComparator = comparator;
70      }
71  
72      /** Annotations defined on the parameters of a method. */
73      private ParameterAnnotationEntry[] parameterAnnotationEntries;
74  
75      /**
76       * Empty constructor, all attributes have to be defined via 'setXXX' methods. Use at your own risk.
77       */
78      public Method() {
79      }
80  
81      /**
82       * Constructs a Method from a data input using standard Code headers.
83       *
84       * @param file Input stream.
85       * @param constantPool The constant pool.
86       * @throws IOException Thrown if an I/O error occurs.
87       * @throws ClassFormatException Thrown if the method or one of its attributes is malformed.
88       */
89      Method(final DataInput file, final ConstantPool constantPool) throws IOException, ClassFormatException {
90          this(file, constantPool, false);
91      }
92  
93      /**
94       * Constructs a Method from a data input using the selected Code header layout.
95       *
96       * @param file Input stream.
97       * @param constantPool The constant pool.
98       * @param compactCodeHeader Whether to read any Code attributes encountered with compact four-byte headers ({@code true})
99       *        or standard eight-byte headers ({@code false}).
100      * @throws IOException Thrown if an I/O error occurs.
101      * @throws ClassFormatException Thrown if the method or one of its attributes is malformed.
102      * @see Attribute#readAttribute(DataInput, ConstantPool, boolean)
103      */
104     Method(final DataInput file, final ConstantPool constantPool, final boolean compactCodeHeader) throws IOException {
105         super(file, constantPool, compactCodeHeader);
106     }
107 
108     /**
109      * Constructs a Method.
110      *
111      * @param accessFlags Access rights of method.
112      * @param nameIndex Points to method name in constant pool.
113      * @param signatureIndex Points to encoded signature.
114      * @param attributes Collection of attributes.
115      * @param constantPool Array of constants.
116      */
117     public Method(final int accessFlags, final int nameIndex, final int signatureIndex, final Attribute[] attributes, final ConstantPool constantPool) {
118         super(accessFlags, nameIndex, signatureIndex, attributes, constantPool);
119     }
120 
121     /**
122      * Initialize from another object. Note that both objects use the same references (shallow copy). Use clone() for a
123      * physical copy.
124      *
125      * @param c Source to copy.
126      */
127     public Method(final Method c) {
128         super(c);
129     }
130 
131     /**
132      * Called by objects that are traversing the nodes of the tree implicitly defined by the contents of a Java class.
133      * That is, the hierarchy of methods, fields, attributes, and other elements forms a tree of objects.
134      *
135      * @param v Visitor object.
136      */
137     @Override
138     public void accept(final Visitor v) {
139         v.visitMethod(this);
140     }
141 
142     /**
143      * Creates a deep copy of this method.
144      *
145      * @param constantPool The constant pool.
146      * @return deep copy of this method.
147      */
148     public Method copy(final ConstantPool constantPool) {
149         return (Method) copy_(constantPool);
150     }
151 
152     /**
153      * Return value as defined by given BCELComparator strategy. By default two method objects are said to be equal when
154      * their names and signatures are equal.
155      *
156      * @see Object#equals(Object)
157      */
158     @Override
159     public boolean equals(final Object obj) {
160         return obj instanceof Method && bcelComparator.equals(this, (Method) obj);
161     }
162 
163     /**
164      * Gets an array of method argument types.
165      *
166      * @return array of method argument types.
167      */
168     public Type[] getArgumentTypes() {
169         return Type.getArgumentTypes(getSignature());
170     }
171 
172     /**
173      * Gets the Code attribute of the method, if any.
174      *
175      * @return Code attribute of method, if any.
176      */
177     public Code getCode() {
178         for (final Attribute attribute : super.getAttributes()) {
179             if (attribute instanceof Code) {
180                 return (Code) attribute;
181             }
182         }
183         return null;
184     }
185 
186     /**
187      * Gets the ExceptionTable attribute of the method, if any.
188      *
189      * @return ExceptionTable attribute of method, if any, that is, list all exceptions the method may throw not exception handlers.
190      */
191     public ExceptionTable getExceptionTable() {
192         for (final Attribute attribute : super.getAttributes()) {
193             if (attribute instanceof ExceptionTable) {
194                 return (ExceptionTable) attribute;
195             }
196         }
197         return null;
198     }
199 
200     /**
201      * Gets the LineNumberTable of the code attribute, if any.
202      *
203      * @return LineNumberTable of code attribute if any, for example the call is forwarded to the Code attribute.
204      */
205     public LineNumberTable getLineNumberTable() {
206         final Code code = getCode();
207         if (code == null) {
208             return null;
209         }
210         return code.getLineNumberTable();
211     }
212 
213     /**
214      * Gets the LocalVariableTable of the code attribute, if any.
215      *
216      * @return LocalVariableTable of code attribute if any, for example the call is forwarded to the Code attribute.
217      */
218     public LocalVariableTable getLocalVariableTable() {
219         final Code code = getCode();
220         if (code == null) {
221             return null;
222         }
223         return code.getLocalVariableTable();
224     }
225 
226     /**
227      * Gets the local variable type table attribute {@link LocalVariableTypeTable}.
228      *
229      * @return LocalVariableTypeTable of code attribute if any, for example the call is forwarded to the Code attribute.
230      * @since 6.10.0
231      */
232     public LocalVariableTypeTable getLocalVariableTypeTable() {
233         final Code code = getCode();
234         if (code == null) {
235             return null;
236         }
237         return code.getLocalVariableTypeTable();
238     }
239 
240     /**
241      * Gets the annotations on the parameters of a method.
242      *
243      * @return Annotations on the parameters of a method.
244      * @since 6.0
245      */
246     public ParameterAnnotationEntry[] getParameterAnnotationEntries() {
247         if (parameterAnnotationEntries == null) {
248             parameterAnnotationEntries = ParameterAnnotationEntry.createParameterAnnotationEntries(getAttributes());
249         }
250         return parameterAnnotationEntries;
251     }
252 
253     /**
254      * Gets return type of method.
255      *
256      * @return return type of method.
257      */
258     public Type getReturnType() {
259         return Type.getReturnType(getSignature());
260     }
261 
262     /**
263      * Return value as defined by given BCELComparator strategy. By default return the hash code of the method's name XOR
264      * signature.
265      *
266      * @see Object#hashCode()
267      */
268     @Override
269     public int hashCode() {
270         return bcelComparator.hashCode(this);
271     }
272 
273     /**
274      * Return string representation close to declaration format, 'public static void main(String[] args) throws
275      * IOException', for example.
276      *
277      * @return String representation of the method.
278      */
279     @Override
280     public String toString() {
281         final String access = Utility.accessToString(super.getAccessFlags());
282         // Get name and signature from constant pool
283         ConstantUtf8 c = super.getConstantPool().getConstantUtf8(super.getSignatureIndex());
284         String signature = c.getBytes();
285         c = super.getConstantPool().getConstantUtf8(super.getNameIndex());
286         final String name = c.getBytes();
287         signature = Utility.methodSignatureToString(signature, name, access, true, getLocalVariableTable());
288         final StringBuilder buf = new StringBuilder(signature);
289         for (final Attribute attribute : super.getAttributes()) {
290             if (!(attribute instanceof Code || attribute instanceof ExceptionTable)) {
291                 buf.append(" [").append(attribute).append("]");
292             }
293         }
294         final ExceptionTable e = getExceptionTable();
295         if (e != null) {
296             final String str = e.toString();
297             if (!str.isEmpty()) {
298                 buf.append("\n\t\tthrows ").append(str);
299             }
300         }
301         return buf.toString();
302     }
303 }
304