javassist.bytecode.ClassFile Java Examples

The following examples show how to use javassist.bytecode.ClassFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavasisstUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenTableOfInstructions_whenAddNewInstruction_thenShouldConstructProperSequence() throws NotFoundException, BadBytecode, CannotCompileException, IllegalAccessException, InstantiationException {
    // given
    ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.ThreeDimensionalPoint").getClassFile();

    // when
    FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I");
    f.setAccessFlags(AccessFlag.PUBLIC);
    cf.addField(f);

    ClassPool classPool = ClassPool.getDefault();
    Field[] fields = classPool.makeClass(cf).toClass().getFields();
    List<String> fieldsList = Stream.of(fields).map(Field::getName).collect(Collectors.toList());
    assertTrue(fieldsList.contains("id"));

}
 
Example #2
Source File: JavasisstUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenJavaClass_whenLoadAtByJavassist_thenTraversWholeClass() throws NotFoundException, CannotCompileException, BadBytecode {
    // given
    ClassPool cp = ClassPool.getDefault();
    ClassFile cf = cp.get("com.baeldung.javasisst.Point").getClassFile();
    MethodInfo minfo = cf.getMethod("move");
    CodeAttribute ca = minfo.getCodeAttribute();
    CodeIterator ci = ca.iterator();

    // when
    List<String> operations = new LinkedList<>();
    while (ci.hasNext()) {
        int index = ci.next();
        int op = ci.byteAt(index);
        operations.add(Mnemonic.OPCODE[op]);
    }

    // then
    assertEquals(operations, Arrays.asList("aload_0", "iload_1", "putfield", "aload_0", "iload_2", "putfield", "return"));

}
 
Example #3
Source File: JavasisstUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenJavasisstAPI_whenConstructClass_thenGenerateAClassFile() throws CannotCompileException, IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
    // given
    String classNameWithPackage = "com.baeldung.JavassistGeneratedClass";
    ClassFile cf = new ClassFile(false, classNameWithPackage, null);
    cf.setInterfaces(new String[] { "java.lang.Cloneable" });

    FieldInfo f = new FieldInfo(cf.getConstPool(), "id", "I");
    f.setAccessFlags(AccessFlag.PUBLIC);
    cf.addField(f);

    // when
    String className = "JavassistGeneratedClass.class";
    cf.write(new DataOutputStream(new FileOutputStream(className)));

    // then
    ClassPool classPool = ClassPool.getDefault();
    Field[] fields = classPool.makeClass(cf).toClass().getFields();
    assertEquals(fields[0].getName(), "id");

    String classContent = new String(Files.readAllBytes(Paths.get(className)));
    assertTrue(classContent.contains("java/lang/Cloneable"));
}
 
Example #4
Source File: ClassPathScanner.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void scan(final Object cls) {
  final ClassFile classFile = (ClassFile)cls;
  AnnotationsAttribute annotations = ((AnnotationsAttribute)classFile.getAttribute(AnnotationsAttribute.visibleTag));
  if (annotations != null) {
    boolean isAnnotated = false;
    for (javassist.bytecode.annotation.Annotation a : annotations.getAnnotations()) {
      if (annotationsToScan.contains(a.getTypeName())) {
        isAnnotated = true;
      }
    }
    if (isAnnotated) {
      List<AnnotationDescriptor> classAnnotations = getAnnotationDescriptors(annotations);
      List<FieldInfo> classFields = classFile.getFields();
      List<FieldDescriptor> fieldDescriptors = new ArrayList<>(classFields.size());
      for (FieldInfo field : classFields) {
        String fieldName = field.getName();
        AnnotationsAttribute fieldAnnotations = ((AnnotationsAttribute) field.getAttribute(AnnotationsAttribute.visibleTag));
        fieldDescriptors.add(new FieldDescriptor(fieldName, field.getDescriptor(), getAnnotationDescriptors(fieldAnnotations)));
      }
      functions.add(new AnnotatedClassDescriptor(classFile.getName(), classAnnotations, fieldDescriptors));
    }
  }
}
 
Example #5
Source File: ClassFileArchiveEntryHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handleEntry(ArchiveEntry entry, ArchiveContext context) {
	// Ultimately we'd like to leverage Jandex here as long term we want to move to
	// using Jandex for annotation processing.  But even then, Jandex atm does not have
	// any facility for passing a stream and conditionally indexing it into an Index or
	// returning existing ClassInfo objects.
	//
	// So not sure we can ever not do this unconditional input stream read :(
	final ClassFile classFile = toClassFile( entry );
	final ClassDescriptor classDescriptor = toClassDescriptor( classFile, entry );

	if ( classDescriptor.getCategorization() == ClassDescriptor.Categorization.OTHER ) {
		return;
	}

	resultCollector.handleClass( classDescriptor, context.isRootUrl() );
}
 
Example #6
Source File: BulkAccessorFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
BulkAccessor create() {
	final Method[] getters = new Method[getterNames.length];
	final Method[] setters = new Method[setterNames.length];
	findAccessors( targetBean, getterNames, setterNames, types, getters, setters );

	final Class beanClass;
	try {
		final ClassFile classfile = make( getters, setters );
		final ClassLoader loader = this.getClassLoader();
		if ( writeDirectory != null ) {
			FactoryHelper.writeFile( classfile, writeDirectory );
		}

		beanClass = FactoryHelper.toClass( classfile, loader, getDomain() );
		return (BulkAccessor) this.newInstance( beanClass );
	}
	catch ( Exception e ) {
		throw new BulkAccessorException( e.getMessage(), e );
	}
}
 
Example #7
Source File: CtMethodBuilder.java    From japicmp with Apache License 2.0 6 votes vote down vote up
public CtMethod addToClass(CtClass declaringClass) throws CannotCompileException {
	if (this.returnType == null) {
		this.returnType = declaringClass;
	}
	CtMethod ctMethod = CtNewMethod.make(this.modifier, this.returnType, this.name, this.parameters, this.exceptions, this.body, declaringClass);
	ctMethod.setModifiers(this.modifier);
	declaringClass.addMethod(ctMethod);
	for (String annotation : annotations) {
		ClassFile classFile = declaringClass.getClassFile();
		ConstPool constPool = classFile.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		Annotation annot = new Annotation(annotation, constPool);
		attr.setAnnotation(annot);
		ctMethod.getMethodInfo().addAttribute(attr);
	}
	return ctMethod;
}
 
Example #8
Source File: ClassFileArchiveEntryHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private ClassDescriptor toClassDescriptor(ClassFile classFile, ArchiveEntry entry) {
	ClassDescriptor.Categorization categorization = ClassDescriptor.Categorization.OTHER;;

	final AnnotationsAttribute visibleAnnotations = (AnnotationsAttribute) classFile.getAttribute( AnnotationsAttribute.visibleTag );
	if ( visibleAnnotations != null ) {
		if ( visibleAnnotations.getAnnotation( Entity.class.getName() ) != null
				|| visibleAnnotations.getAnnotation( MappedSuperclass.class.getName() ) != null
				|| visibleAnnotations.getAnnotation( Embeddable.class.getName() ) != null ) {
			categorization = ClassDescriptor.Categorization.MODEL;
		}
		else if ( visibleAnnotations.getAnnotation( Converter.class.getName() ) != null ) {
			categorization = ClassDescriptor.Categorization.CONVERTER;
		}
	}

	return new ClassDescriptorImpl( classFile.getName(), categorization, entry.getStreamAccess() );
}
 
Example #9
Source File: MethodAnnotationSelector.java    From panda with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<Method> select(AnnotationsScannerProcess process, AnnotationScannerStore store) {
    Set<String> selectedClasses = new HashSet<>();
    MetadataAdapter<ClassFile, FieldInfo, MethodInfo> adapter = process.getMetadataAdapter();

    for (ClassFile cachedClassFile : store.getCachedClassFiles()) {
        for (MethodInfo method : adapter.getMethods(cachedClassFile)) {
            for (String annotationName : adapter.getMethodAnnotationNames(method)) {
                if (annotationType.getName().equals(annotationName)) {
                    selectedClasses.add(adapter.getMethodFullKey(cachedClassFile, method));
                }
            }
        }
    }

    return AnnotationsScannerUtils.forMethods(process, selectedClasses);
}
 
Example #10
Source File: JavasisstUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenLoadedClass_whenAddConstructorToClass_shouldCreateClassWithConstructor() throws NotFoundException, CannotCompileException, BadBytecode {
    // given
    ClassFile cf = ClassPool.getDefault().get("com.baeldung.javasisst.Point").getClassFile();
    Bytecode code = new Bytecode(cf.getConstPool());
    code.addAload(0);
    code.addInvokespecial("java/lang/Object", MethodInfo.nameInit, "()V");
    code.addReturn(null);

    // when
    MethodInfo minfo = new MethodInfo(cf.getConstPool(), MethodInfo.nameInit, "()V");
    minfo.setCodeAttribute(code.toCodeAttribute());
    cf.addMethod(minfo);

    // then
    CodeIterator ci = code.toCodeAttribute().iterator();
    List<String> operations = new LinkedList<>();
    while (ci.hasNext()) {
        int index = ci.next();
        int op = ci.byteAt(index);
        operations.add(Mnemonic.OPCODE[op]);
    }

    assertEquals(operations, Arrays.asList("aload_0", "invokespecial", "return"));

}
 
Example #11
Source File: FieldTransformer.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private int transformInvokevirtualsIntoGetfields(ClassFile classfile,
                                                 CodeIterator iter, int pos) {
	ConstPool cp = classfile.getConstPool();
	int c = iter.byteAt(pos);
	if (c != Opcode.GETFIELD) {
		return pos;
	}
	int index = iter.u16bitAt(pos + 1);
	String fieldName = cp.getFieldrefName(index);
	String className = cp.getFieldrefClassName(index);
	if ((!classfile.getName().equals(className))
	    || (!readableFields.containsKey(fieldName))) {
		return pos;
	}
	String desc = "()" + (String) readableFields.get(fieldName);
	int read_method_index = cp.addMethodrefInfo(cp.getThisClassInfo(),
	                                            EACH_READ_METHOD_PREFIX + fieldName, desc);
	iter.writeByte(Opcode.INVOKEVIRTUAL, pos);
	iter.write16bit(read_method_index, pos + 1);
	return pos;
}
 
Example #12
Source File: BulkAccessorFactory.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Declares a constructor that takes no parameter.
 *
 * @param classfile
 * @throws CannotCompileException
 */
private void addDefaultConstructor(ClassFile classfile) throws CannotCompileException {
	ConstPool cp = classfile.getConstPool();
	String cons_desc = "()V";
	MethodInfo mi = new MethodInfo( cp, MethodInfo.nameInit, cons_desc );

	Bytecode code = new Bytecode( cp, 0, 1 );
	// aload_0
	code.addAload( 0 );
	// invokespecial
	code.addInvokespecial( BulkAccessor.class.getName(), MethodInfo.nameInit, cons_desc );
	// return
	code.addOpcode( Opcode.RETURN );

	mi.setCodeAttribute( code.toCodeAttribute() );
	mi.setAccessFlags( AccessFlag.PUBLIC );
	classfile.addMethod( mi );
}
 
Example #13
Source File: FieldTransformer.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void addReadWriteMethods(ClassFile classfile)
		throws CannotCompileException {
	List fields = classfile.getFields();
	for (Iterator field_iter = fields.iterator(); field_iter.hasNext();) {
		FieldInfo finfo = (FieldInfo) field_iter.next();
		if ((finfo.getAccessFlags() & AccessFlag.STATIC) == 0
		    && (!finfo.getName().equals(HANDLER_FIELD_NAME))) {
			// case of non-static field
			if (filter.handleRead(finfo.getDescriptor(), finfo
					.getName())) {
				addReadMethod(classfile, finfo);
				readableFields.put(finfo.getName(), finfo
						.getDescriptor());
			}
			if (filter.handleWrite(finfo.getDescriptor(), finfo
					.getName())) {
				addWriteMethod(classfile, finfo);
				writableFields.put(finfo.getName(), finfo
						.getDescriptor());
			}
		}
	}
}
 
Example #14
Source File: FieldTransformer.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void addSetFieldHandlerMethod(ClassFile classfile)
		throws CannotCompileException {
	ConstPool cp = classfile.getConstPool();
	int this_class_index = cp.getThisClassInfo();
	MethodInfo minfo = new MethodInfo(cp, SETFIELDHANDLER_METHOD_NAME,
	                                  SETFIELDHANDLER_METHOD_DESCRIPTOR);
	/* local variables | this | callback | */
	Bytecode code = new Bytecode(cp, 3, 3);
	// aload_0 // load this
	code.addAload(0);
	// aload_1 // load callback
	code.addAload(1);
	// putfield // put field "$JAVASSIST_CALLBACK" defined already
	code.addOpcode(Opcode.PUTFIELD);
	int field_index = cp.addFieldrefInfo(this_class_index,
	                                     HANDLER_FIELD_NAME, HANDLER_FIELD_DESCRIPTOR);
	code.addIndex(field_index);
	// return
	code.addOpcode(Opcode.RETURN);
	minfo.setCodeAttribute(code.toCodeAttribute());
	minfo.setAccessFlags(AccessFlag.PUBLIC);
	classfile.addMethod(minfo);
}
 
Example #15
Source File: JavassistUtils.java    From statefulj with Apache License 2.0 5 votes vote down vote up
public static void copyTypeAnnotations(Class<?> fromClass, CtClass toClass) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
	for(java.lang.annotation.Annotation annotation :  fromClass.getAnnotations()) {
		if (!StatefulController.class.isAssignableFrom(annotation.annotationType())) {
			ClassFile ccFile = toClass.getClassFile();
			AnnotationsAttribute attr = getAnnotationsAttribute(ccFile);
			Annotation clone = cloneAnnotation(ccFile.getConstPool(), annotation);
			attr.addAnnotation(clone);
		}
	}
}
 
Example #16
Source File: URLFilter.java    From panda with Apache License 2.0 5 votes vote down vote up
@Override
public boolean check(MetadataAdapter<ClassFile, FieldInfo, MethodInfo> metadataAdapter, URL element) {
    String url = element.toString();

    for (String path : paths) {
        if (url.contains(path)) {
            return !exclude;
        }
    }

    return exclude;
}
 
Example #17
Source File: DefaultRepositoryGenerator.java    From business with Mozilla Public License 2.0 5 votes vote down vote up
Class<? extends T> generate(Class<? extends Repository> baseImpl) {
    try {
        CtClass cc = createClass(
                getClassName(baseImpl, getCounter(repositoryInterface).incrementAndGet()),
                baseImpl
        );
        ClassFile cf = cc.getClassFile();
        ConstPool constPool = cf.getConstPool();

        cc.setModifiers(Modifier.PUBLIC);

        cc.setInterfaces(new CtClass[]{classPool.getCtClass(repositoryInterface.getName())});

        if (hasGenericConstructor(baseImpl)) {
            cc.addConstructor(createConstructor(constPool, cc));
        } else {
            cc.addConstructor(createDefaultConstructor(cc));
        }

        cf.addAttribute(createQualifierAttribute(constPool, getQualifier(baseImpl)
                .orElseThrow(() -> new NotFoundException("Qualifier annotation not found"))));

        return cast(cc.toClass(
                classLoader,
                DefaultRepositoryCollector.class.getProtectionDomain())
        );
    } catch (CannotCompileException | NotFoundException e) {
        throw BusinessException.wrap(e, BusinessErrorCode.UNABLE_TO_CREATE_DEFAULT_IMPLEMENTATION)
                .put("interface", repositoryInterface)
                .put("base", baseImpl);
    }
}
 
Example #18
Source File: AnnotationsScannerProcessWorker.java    From panda with Apache License 2.0 5 votes vote down vote up
private Collection<@Nullable ClassFile> scanResource(AnnotationsScannerResource<?> resource) {
    for (AnnotationsFilter<URL> urlFilter : process.getProcessConfiguration().urlFilters) {
        if (!urlFilter.check(process.getMetadataAdapter(), resource.getLocation())) {
            return Collections.emptyList();
        }
    }

    Collection<ClassFile> classFiles = new ArrayList<>(512);

    for (@Nullable AnnotationsScannerFile annotationsScannerFile : resource) {
        if (annotationsScannerFile == null) {
            continue;
        }

        long time = System.nanoTime();
        ClassFile classFile = scanFile(annotationsScannerFile);
        fileTime += (System.nanoTime() - time);

        if (classFile == null) {
            continue;
        }

        classFiles.add(classFile);
    }

    return classFiles;
}
 
Example #19
Source File: JInterface.java    From jadira with Apache License 2.0 5 votes vote down vote up
public Set<JClass> getImplementingClasses() {
    
    Set<JClass> retVal = new HashSet<JClass>();
    List<? extends ClassFile> classes = getResolver().getClassFileResolver().resolveAll(null, CLASSPATH_PROJECTOR, new JClassImplementsFilter(this.getActualClass()), new JElementTypeFilter(JClass.class)); 
    for (ClassFile classFile : classes) {
        retVal.add(JClass.getJClass(classFile, getResolver()));
    }
    return retVal;
}
 
Example #20
Source File: JavassistAdapter.java    From panda with Apache License 2.0 5 votes vote down vote up
@Override
public ClassFile getOfCreateClassObject(AnnotationsScanner scanner, AnnotationsScannerFile file) throws Exception {
    InputStream inputStream = null;

    try {
        inputStream = file.openInputStream();
        DataInputStream dis = new DataInputStream(new BufferedInputStream(inputStream));
        return new ClassFile(dis);
    } finally {
        IOUtils.close(inputStream);
    }
}
 
Example #21
Source File: CheckForConcept.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public String getClassName(String name, InputStream stream) throws IOException {
	DataInputStream dstream = new DataInputStream(stream);
	try {
		ClassFile cf = new ClassFile(dstream);
		if (checkAccessFlags(cf.getAccessFlags())) {
			if (isAnnotationPresent(cf))
				return cf.getName();
		}
	} finally {
		dstream.close();
	}
	return null;
}
 
Example #22
Source File: CtFieldBuilder.java    From japicmp with Apache License 2.0 5 votes vote down vote up
public CtField addToClass(CtClass ctClass) throws CannotCompileException {
	CtField ctField = new CtField(this.type, this.name, ctClass);
	ctField.setModifiers(this.modifier);
	if (constantValue != null) {
		if (constantValue instanceof Boolean) {
			ctClass.addField(ctField, CtField.Initializer.constant((Boolean) constantValue));
		} else if (constantValue instanceof Integer) {
			ctClass.addField(ctField, CtField.Initializer.constant((Integer) constantValue));
		} else if (constantValue instanceof Long) {
			ctClass.addField(ctField, CtField.Initializer.constant((Long) constantValue));
		} else if (constantValue instanceof String) {
			ctClass.addField(ctField, CtField.Initializer.constant((String) constantValue));
		} else {
			throw new IllegalArgumentException("Provided constant value for field is of unsupported type: " + constantValue.getClass().getName());
		}
	} else {
		ctClass.addField(ctField);
	}
	for (String annotation : annotations) {
		ClassFile classFile = ctClass.getClassFile();
		ConstPool constPool = classFile.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		Annotation annot = new Annotation(annotation, constPool);
		attr.setAnnotation(annot);
		ctField.getFieldInfo().addAttribute(attr);
	}
	return ctField;
}
 
Example #23
Source File: IgniteExamplesMLTestSuite.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates test class for given example.
 *
 * @param exampleCls Class of the example to be tested.
 * @return Test class.
 */
private static Class<?> makeTestClass(Class<?> exampleCls) {
    ClassPool cp = ClassPool.getDefault();
    cp.insertClassPath(new ClassClassPath(IgniteExamplesMLTestSuite.class));

    CtClass cl = cp.makeClass(basePkgForTests + "." + exampleCls.getSimpleName() + "SelfTest");

    try {
        cl.setSuperclass(cp.get(GridAbstractExamplesTest.class.getName()));

        CtMethod mtd = CtNewMethod.make("public void testExample() { "
            + exampleCls.getCanonicalName()
            + ".main("
            + MLExamplesCommonArgs.class.getName()
            + ".EMPTY_ARGS_ML); }", cl);

        // Create and add annotation.
        ClassFile ccFile = cl.getClassFile();
        ConstPool constpool = ccFile.getConstPool();

        AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
        Annotation annot = new Annotation("org.junit.Test", constpool);

        attr.addAnnotation(annot);
        mtd.getMethodInfo().addAttribute(attr);

        cl.addMethod(mtd);

        return cl.toClass();
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: EmbeddedGobblin.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * This returns the set of jars required by a basic Gobblin ingestion job. In general, these need to be distributed
 * to workers in a distributed environment.
 */
private void loadCoreGobblinJarsToDistributedJars() {
  // Gobblin-api
  distributeJarByClassWithPriority(State.class, 0);
  // Gobblin-core
  distributeJarByClassWithPriority(ConstructState.class, 0);
  // Gobblin-core-base
  distributeJarByClassWithPriority(InstrumentedExtractorBase.class, 0);
  // Gobblin-metrics-base
  distributeJarByClassWithPriority(MetricContext.class, 0);
  // Gobblin-metrics
  distributeJarByClassWithPriority(GobblinMetrics.class, 0);
  // Gobblin-metastore
  distributeJarByClassWithPriority(FsStateStore.class, 0);
  // Gobblin-runtime
  distributeJarByClassWithPriority(Task.class, 0);
  // Gobblin-utility
  distributeJarByClassWithPriority(PathUtils.class, 0);
  // joda-time
  distributeJarByClassWithPriority(ReadableInstant.class, 0);
  // guava
  distributeJarByClassWithPriority(Escaper.class, -10); // Escaper was added in guava 15, so we use it to identify correct jar
  // dropwizard.metrics-core
  distributeJarByClassWithPriority(MetricFilter.class, 0);
  // pegasus
  distributeJarByClassWithPriority(DataTemplate.class, 0);
  // commons-lang3
  distributeJarByClassWithPriority(ClassUtils.class, 0);
  // avro
  distributeJarByClassWithPriority(SchemaBuilder.class, 0);
  // guava-retry
  distributeJarByClassWithPriority(RetryListener.class, 0);
  // config
  distributeJarByClassWithPriority(ConfigFactory.class, 0);
  // reflections
  distributeJarByClassWithPriority(Reflections.class, 0);
  // javassist
  distributeJarByClassWithPriority(ClassFile.class, 0);
}
 
Example #25
Source File: AnnotationDB.java    From audit4j-core with Apache License 2.0 5 votes vote down vote up
protected void scanClass(ClassFile cf) {
    String className = cf.getName();
    AnnotationsAttribute visible = (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag);
    AnnotationsAttribute invisible = (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.invisibleTag);
    if (visible != null)
        populate(visible.getAnnotations(), className);
    if (invisible != null)
        populate(invisible.getAnnotations(), className);
}
 
Example #26
Source File: JPackage.java    From jadira with Apache License 2.0 5 votes vote down vote up
public Set<JInterface> getInterfaces() throws ClasspathAccessException {

        Set<JInterface> retVal = new HashSet<JInterface>();
        List<? extends ClassFile> classes = getResolver().getClassFileResolver().resolveAll(null, CLASSPATH_PROJECTOR, new PackageFileFilter(getName(), false), new PackageFilter(this), new JElementTypeFilter(JInterface.class));
        for (ClassFile classFile : classes) {
            if (classFile.isInterface() && (!classFile.getSuperclass().equals("java.lang.annotation.Annotation"))) {
                retVal.add(JInterface.getJInterface(classFile, getResolver()));
            }
        }
        return retVal;
    }
 
Example #27
Source File: AnnotationDB.java    From audit4j-core with Apache License 2.0 5 votes vote down vote up
protected void scanFields(ClassFile cf) {
    List<ClassFile> fields = cf.getFields();
    if (fields == null)
        return;
    for (Object obj : fields) {
        FieldInfo field = (FieldInfo) obj;
        AnnotationsAttribute visible = (AnnotationsAttribute) field.getAttribute(AnnotationsAttribute.visibleTag);
        AnnotationsAttribute invisible = (AnnotationsAttribute) field
                .getAttribute(AnnotationsAttribute.invisibleTag);
        if (visible != null)
            populate(visible.getAnnotations(), cf.getName());
        if (invisible != null)
            populate(invisible.getAnnotations(), cf.getName());
    }
}
 
Example #28
Source File: FieldTransformer.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void addFieldHandledInterface(ClassFile classfile) {
	String[] interfaceNames = classfile.getInterfaces();
	String[] newInterfaceNames = new String[interfaceNames.length + 1];
	System.arraycopy(interfaceNames, 0, newInterfaceNames, 0,
	                 interfaceNames.length);
	newInterfaceNames[newInterfaceNames.length - 1] = FIELD_HANDLED_TYPE_NAME;
	classfile.setInterfaces(newInterfaceNames);
}
 
Example #29
Source File: ClassPathScanner.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public void scan(final Object cls) {
  final ClassFile classFile = (ClassFile)cls;
  String className = classFile.getName();
  String superclass = classFile.getSuperclass();
  boolean isAbstract = (classFile.getAccessFlags() & (AccessFlag.INTERFACE | AccessFlag.ABSTRACT)) != 0;
  ChildClassDescriptor scannedClass = new ChildClassDescriptor(className, isAbstract);
  if (!superclass.equals(Object.class.getName())) {
    children.put(superclass, scannedClass);
  }
  for (String anInterface : classFile.getInterfaces()) {
    children.put(anInterface, scannedClass);
  }
}
 
Example #30
Source File: CheckForAnnotation.java    From anno4j with Apache License 2.0 5 votes vote down vote up
protected boolean isAnnotationPresent(ClassFile cf) {
	List<MethodInfo> methods = cf.getMethods();
	for (MethodInfo info : methods) {
		AnnotationsAttribute attr = (AnnotationsAttribute) info
				.getAttribute(AnnotationsAttribute.visibleTag);
		if (isAnnotationPresent(attr))
			return true;
	}
	return false;
}