javassist.bytecode.FieldInfo Java Examples

The following examples show how to use javassist.bytecode.FieldInfo. 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: JavassistAdapter.java    From panda with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isPublic(@Nullable Object o) {
    if (o == null) {
        return false;
    }

    if (o instanceof ClassFile) {
        return AccessFlag.isPublic(((ClassFile) o).getAccessFlags());
    }

    if (o instanceof MethodInfo) {
        return AccessFlag.isPublic(((MethodInfo) o).getAccessFlags());
    }

    if (o instanceof FieldInfo) {
        return AccessFlag.isPublic(((FieldInfo) o).getAccessFlags());
    }

    if (o instanceof Class) {
        return Modifier.isPublic(((Class) o).getModifiers());
    }

    return false;
}
 
Example #3
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 #4
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 6 votes vote down vote up
private ArrayList<Signature> getDeclaredFields(boolean areStatic) {
    if ((areStatic ? this.fieldsStatic : this.fieldsObject) == null) {
        final ArrayList<Signature> fields = new ArrayList<Signature>();
        final List<FieldInfo> fieldsJA = this.cf.getFields();
        for (FieldInfo fld : fieldsJA) {
            if (Modifier.isStatic(AccessFlag.toModifier(fld.getAccessFlags())) == areStatic) {
                final Signature sig = new Signature(getClassName(), fld.getDescriptor(), fld.getName());
                fields.add(sig);
            }
        }
        if (areStatic) {
            this.fieldsStatic = fields;
        } else {
            this.fieldsObject = fields;
        }
    }
    return (areStatic ? this.fieldsStatic : this.fieldsObject);
}
 
Example #5
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 #6
Source File: JClass.java    From jadira with Apache License 2.0 6 votes vote down vote up
public List<JField> getFields() {

    	boolean isJavaLangThrowable = "java.lang.Throwable".equals(this.getName());
    	boolean isJavaLangSystem = "java.lang.System".equals(this.getName());
    	
        final List<JField> retVal = new ArrayList<JField>();
        @SuppressWarnings("unchecked")
        final List<FieldInfo> fields = (List<FieldInfo>) getClassFile().getFields();

        for (FieldInfo next : fields) {
        	if (isJavaLangThrowable && ("backtrace".equals(next.getName()))) {
        		// See http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=d7621f5189c86f127fe5737490903?bug_id=4496456
        		continue;
        	}
        	if (isJavaLangSystem && ("security".equals(next.getName()))) {
                continue;
            }
            retVal.add(JField.getJField(next, this, getResolver()));
        }
        return retVal;
    }
 
Example #7
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 #8
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 #9
Source File: JavassistProxy.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
/**
 * 代理缓存字段
 * 
 * <pre>
 * private final [clazz.name] _object;
 * private final CacheManager _manager;
 * </pre>
 * 
 * @param clazz
 * @param proxyClass
 * @throws Exception
 */
private void proxyCacheFields(Class<?> clazz, CtClass proxyClass) throws Exception {
    ConstPool constPool = proxyClass.getClassFile2().getConstPool();
    CtField managerField = new CtField(classPool.get(ProxyManager.class.getName()), FIELD_MANAGER, proxyClass);
    CtField informationField = new CtField(classPool.get(CacheInformation.class.getName()), FIELD_INFORMATION, proxyClass);

    List<CtField> fields = Arrays.asList(managerField, informationField);
    List<String> types = Arrays.asList("javax.persistence.Transient", "org.springframework.data.annotation.Transient");
    for (CtField field : fields) {
        field.setModifiers(Modifier.PRIVATE + Modifier.FINAL + Modifier.TRANSIENT);
        FieldInfo fieldInfo = field.getFieldInfo();
        for (String type : types) {
            AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
            Annotation annotation = new Annotation(type, constPool);
            annotationsAttribute.addAnnotation(annotation);
            fieldInfo.addAttribute(annotationsAttribute);
        }
        proxyClass.addField(field);
    }
}
 
Example #10
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isFieldFinal(Signature fieldSignature) throws FieldNotFoundException {
    final FieldInfo fld = findField(fieldSignature);
    if (fld == null) {
        throw new FieldNotFoundException(fieldSignature.toString());
    }
    return Modifier.isFinal(AccessFlag.toModifier(fld.getAccessFlags()));
}
 
Example #11
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean hasFieldConstantValue(Signature fieldSignature) throws FieldNotFoundException {
    final FieldInfo fld = findField(fieldSignature);
    if (fld == null) {
        throw new FieldNotFoundException(fieldSignature.toString());
    }
    return (fld.getConstantValue() != 0);
}
 
Example #12
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int fieldConstantValueIndex(Signature fieldSignature) throws FieldNotFoundException, AttributeNotFoundException {
    final FieldInfo fld = findField(fieldSignature);
    if (fld == null) {
        throw new FieldNotFoundException(fieldSignature.toString());
    }
    final int cpVal = fld.getConstantValue();
    if (cpVal == 0) {
        throw new AttributeNotFoundException();
    }
    return cpVal;
}
 
Example #13
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isFieldPublic(Signature fieldSignature) throws FieldNotFoundException {
    final FieldInfo fld = findField(fieldSignature);
    if (fld == null) {
        throw new FieldNotFoundException(fieldSignature.toString());
    }
    return Modifier.isPublic(AccessFlag.toModifier(fld.getAccessFlags()));
}
 
Example #14
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 #15
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isFieldPackage(Signature fieldSignature) throws FieldNotFoundException {
    final FieldInfo fld = findField(fieldSignature);
    if (fld == null) {
        throw new FieldNotFoundException(fieldSignature.toString());
    }
    return Modifier.isPackage(AccessFlag.toModifier(fld.getAccessFlags()));
}
 
Example #16
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isFieldPrivate(Signature fieldSignature) throws FieldNotFoundException {
    final FieldInfo fld = findField(fieldSignature);
    if (fld == null) {
        throw new FieldNotFoundException(fieldSignature.toString());
    }
    return Modifier.isPrivate(AccessFlag.toModifier(fld.getAccessFlags()));
}
 
Example #17
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isFieldStatic(Signature fieldSignature) throws FieldNotFoundException {
    final FieldInfo fld = findField(fieldSignature);
    if (fld == null) {
        throw new FieldNotFoundException(fieldSignature.toString());
    }
    return Modifier.isStatic(AccessFlag.toModifier(fld.getAccessFlags()));
}
 
Example #18
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getFieldGenericSignatureType(Signature fieldSignature) 
throws FieldNotFoundException {
    final FieldInfo fld = findField(fieldSignature);
    if (fld == null) {
        throw new FieldNotFoundException(fieldSignature.toString());
    }
    SignatureAttribute sa = (SignatureAttribute) fld.getAttribute(SignatureAttribute.tag);
    return (sa == null ? null : sa.getSignature());
}
 
Example #19
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isFieldProtected(Signature fieldSignature) throws FieldNotFoundException {
    final FieldInfo fld = findField(fieldSignature);
    if (fld == null) {
        throw new FieldNotFoundException(fieldSignature.toString());
    }
    return Modifier.isProtected(AccessFlag.toModifier(fld.getAccessFlags()));
}
 
Example #20
Source File: AnnotationsScannerProcessWorker.java    From panda with Apache License 2.0 5 votes vote down vote up
private @Nullable ClassFile scanFile(AnnotationsScannerFile file) {
    MetadataAdapter<ClassFile, FieldInfo, MethodInfo> metadataAdapter = process.getMetadataAdapter();

    for (AnnotationsFilter<AnnotationsScannerFile> fileFilter : process.getProcessConfiguration().fileFilters) {
        if (!fileFilter.check(metadataAdapter, file)) {
            return null;
        }
    }

    long time = System.nanoTime();
    ClassFile pseudoClass;

    try {
        pseudoClass = metadataAdapter.getOfCreateClassObject(scanner, file);
    } catch (Exception e) {
        return null; // mute
    } finally {
        jaTime += (System.nanoTime() - time);
    }

    for (AnnotationsFilter<ClassFile> pseudoClassFilter : process.getProcessConfiguration().classFileFilters) {
        if (!pseudoClassFilter.check(metadataAdapter, pseudoClass)) {
            return null;
        }
    }

    if (!StringUtils.isEmpty(pseudoClass.getSuperclass())) {
        store.addInheritors(pseudoClass.getSuperclass(), pseudoClass.getName());
    }

    if (pseudoClass.getInterfaces() != null) {
        for (String anInterface : pseudoClass.getInterfaces()) {
            store.addInheritors(anInterface, pseudoClass.getName());
        }
    }

    return pseudoClass;
}
 
Example #21
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int getFieldModifiers(Signature fieldSignature) 
throws FieldNotFoundException {
    final FieldInfo fld = findField(fieldSignature);
    if (fld == null) {
        throw new FieldNotFoundException(fieldSignature.toString());
    }
    return AccessFlag.toModifier(fld.getAccessFlags());
}
 
Example #22
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
@Override
public byte[] getFieldAnnotationsRaw(Signature fieldSignature) 
throws FieldNotFoundException {
    final FieldInfo fld = findField(fieldSignature);
    if (fld == null) {
        throw new FieldNotFoundException(fieldSignature.toString());
    }
    final AttributeInfo attrVisible = fld.getAttribute(AnnotationsAttribute.visibleTag);
    final AttributeInfo attrInvisible = fld.getAttribute(AnnotationsAttribute.invisibleTag);
    return mergeVisibleAndInvisibleAttributes(attrVisible, attrInvisible);
}
 
Example #23
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 #24
Source File: ClassFileJavassist.java    From jbse with GNU General Public License v3.0 5 votes vote down vote up
private FieldInfo findField(Signature fieldSignature) {
    final List<FieldInfo> fieldsJA = this.cf.getFields();
    for (FieldInfo fld : fieldsJA) {
        if (fld.getDescriptor().equals(fieldSignature.getDescriptor()) && 
            fld.getName().equals(fieldSignature.getName())) {
            return fld;
        }
    }
    return null;
}
 
Example #25
Source File: JavassistUtils.java    From statefulj with Apache License 2.0 5 votes vote down vote up
public static void addResourceAnnotation(CtField field, String beanName) {
	FieldInfo fi = field.getFieldInfo();
	
	AnnotationsAttribute attr = new AnnotationsAttribute(
			field.getFieldInfo().getConstPool(), 
			AnnotationsAttribute.visibleTag);
	Annotation annot = new Annotation(Resource.class.getName(), fi.getConstPool());
	
	StringMemberValue nameValue = new StringMemberValue(fi.getConstPool());
	nameValue.setValue(beanName);
	annot.addMemberValue("name", nameValue);
	
	attr.addAnnotation(annot);
	fi.addAttribute(attr);
}
 
Example #26
Source File: FieldTransformer.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void addFieldHandlerField(ClassFile classfile)
		throws CannotCompileException {
	ConstPool cp = classfile.getConstPool();
	FieldInfo finfo = new FieldInfo(cp, HANDLER_FIELD_NAME,
	                                HANDLER_FIELD_DESCRIPTOR);
	finfo.setAccessFlags(AccessFlag.PRIVATE | AccessFlag.TRANSIENT);
	classfile.addField(finfo);
}
 
Example #27
Source File: ClassPathScanner.java    From dremio-oss with Apache License 2.0 5 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);
      @SuppressWarnings("unchecked")
      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));
        final List<AnnotationDescriptor> annotationDescriptors =
            (fieldAnnotations != null) ? getAnnotationDescriptors(fieldAnnotations) : Collections.<AnnotationDescriptor>emptyList();
        fieldDescriptors.add(new FieldDescriptor(fieldName, field.getDescriptor(), annotationDescriptors));
      }
      functions.add(new AnnotatedClassDescriptor(classFile.getName(), classAnnotations, fieldDescriptors));
    }
  }
}
 
Example #28
Source File: JField.java    From jadira with Apache License 2.0 4 votes vote down vote up
protected JField(FieldInfo fieldInfo, JClass jClass, ClasspathResolver resolver) {
    super(fieldInfo.getName(), resolver);
    this.fieldInfo = fieldInfo;
    this.jClass = jClass;
}
 
Example #29
Source File: JField.java    From jadira with Apache License 2.0 4 votes vote down vote up
public static JField getJField(FieldInfo fieldInfo, JClass jClass, ClasspathResolver resolver) {
    return new JField(fieldInfo, jClass, resolver);
}
 
Example #30
Source File: JField.java    From jadira with Apache License 2.0 4 votes vote down vote up
public FieldInfo getFieldInfo() {
    return fieldInfo;
}