View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.lang3.builder;
19  
20  import org.objectweb.asm.ClassWriter;
21  import org.objectweb.asm.MethodVisitor;
22  import org.objectweb.asm.Opcodes;
23  
24  /**
25   * Builds classes dynamically for tests.
26   */
27  public class TestClassBuilder {
28  
29      /**
30       * Extends {@link ClassLoader} to make {@link ClassLoader#defineClass(String, byte[])} public.
31       */
32      static final class DynamicClassLoader extends ClassLoader {
33          public Class<?> defineClass(final String name, final byte[] b) {
34              return defineClass(name, b, 0, b.length);
35          }
36      }
37  
38      /**
39       * Defines the simplest possible class.
40       *
41       * @param name The class name.
42       * @return The new class.
43       */
44      static Class<?> defineSimpleClass(final String name) {
45          final ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
46          classWriter.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, name, null, "java/lang/Object", new String[] {});
47          final MethodVisitor ctor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
48          ctor.visitCode();
49          ctor.visitVarInsn(Opcodes.ALOAD, 0);
50          ctor.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
51          ctor.visitInsn(Opcodes.RETURN);
52          ctor.visitMaxs(1, 1);
53          return new DynamicClassLoader().defineClass(name.replace('/', '.'), classWriter.toByteArray());
54      }
55  
56      static Class<?> defineSimpleClass(final String packageName, final int i) {
57          return defineSimpleClass(packageName.replace('.', '/') + "/C" + i);
58      }
59  
60  }