net.bytebuddy.description.type.TypeDescription.ForLoadedType Java Examples

The following examples show how to use net.bytebuddy.description.type.TypeDescription.ForLoadedType. 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: AsmUtils.java    From Diorite with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Class<T> toClass(TypeDescription type)
{
    if ((type instanceof TypeDescription.ForLoadedType) && (typeHandle != null))
    {
        try
        {
            return (Class<T>) typeHandle.invoke(type);
        }
        catch (Throwable throwable)
        {
            throwable.printStackTrace();
        }
    }
    ClassLoader classLoader = StackWalker.getInstance().getCallerClass().getClassLoader();
    try
    {
        return (Class<T>) Class.forName(type.getActualName(), false, classLoader);
    }
    catch (ClassNotFoundException e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: Controller.java    From Diorite with MIT License 6 votes vote down vote up
<T, B extends AnnotatedCodeElement & NamedElement.WithRuntimeName> ControllerInjectValueData<T> createValue
        (int index, TypeDescription classType, TypeDescription.ForLoadedType.Generic type, B member, String name,
         Map<Class<? extends Annotation>, ? extends Annotation> parentRawScopeAnnotations,
         Map<Class<? extends Annotation>, ? extends Annotation> parentRawQualifierAnnotations)
{
    Map<Class<? extends Annotation>, ? extends Annotation> scopeAnnotations;
    {
        Map<Class<? extends Annotation>, ? extends Annotation> memberRawScopeAnnotations = this.extractRawScopeAnnotations(member);
        Map<Class<? extends Annotation>, Annotation> rawScopeAnnotations = new HashMap<>(parentRawScopeAnnotations);
        rawScopeAnnotations.putAll(memberRawScopeAnnotations);
        scopeAnnotations = this.transformAll(classType, name, member, rawScopeAnnotations);
    }
    Map<Class<? extends Annotation>, ? extends Annotation> qualifierAnnotations;
    {
        Map<Class<? extends Annotation>, ? extends Annotation> memberRawQualifierAnnotations = this.extractRawQualifierAnnotations(member);
        Map<Class<? extends Annotation>, Annotation> rawQualifierAnnotations = new HashMap<>(parentRawQualifierAnnotations);
        rawQualifierAnnotations.putAll(memberRawQualifierAnnotations);
        qualifierAnnotations = this.transformAll(classType, name, member, rawQualifierAnnotations);
    }
    return new ControllerInjectValueData<>(index, name, type, scopeAnnotations, qualifierAnnotations);
}
 
Example #3
Source File: QualifierAndScopeImplementationGenerator.java    From Diorite with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Nullable
public static <T extends Annotation> Class<? extends T> transform(Class<T> clazz)
{
    if (! clazz.isAnnotation() || ! (clazz.isAnnotationPresent(Qualifier.class) || clazz.isAnnotationPresent(Scope.class)))
    {
        return null;
    }
    try
    {
        String name = GENERATED_PREFIX + "." + clazz.getName();
        Unloaded<Object> make = new ByteBuddy(ClassFileVersion.JAVA_V9).subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
                                                                       .implement(Serializable.class, clazz).name(name)
                                                                       .visit(new AnnotationImplementationVisitor(new ForLoadedType(clazz))).make();
        Loaded<Object> load = make.load(ClassLoader.getSystemClassLoader(), Default.INJECTION);
        return (Class<? extends T>) load.getLoaded();
    }
    catch (Throwable e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #4
Source File: ModelClassEnhancer.java    From activejpa with Apache License 2.0 6 votes vote down vote up
@Override
public Builder<?> transform(Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, JavaModule module) {
    logger.info("Transforming the model class - {}", typeDescription.getActualName());
    if (transformedClasses.contains(typeDescription.getActualName())) {
        logger.info("Model class - {} is already transformed. Skipping", typeDescription.getActualName());
        return builder;
    }
    
    builder = defineMethod(builder, typeDescription, classLoader, "all", TargetType.resolve(new ForLoadedType(List.class), typeDescription));
    builder = defineMethod(builder, typeDescription, classLoader, "count", new ForLoadedType(long.class));
    builder = defineMethod(builder, typeDescription, classLoader, "count", new ForLoadedType(long.class), new TypeDescription.ForLoadedType(Filter.class));
    builder = defineMethod(builder, typeDescription, classLoader, "findById", ForGenerifiedErasure.of(new ForLoadedType(Model.class)), new ForLoadedType(Serializable.class));
    builder = defineMethod(builder, typeDescription, classLoader, "deleteAll", TypeDescription.VOID, new TypeDescription.ForLoadedType(Filter.class));
    builder = defineMethod(builder, typeDescription, classLoader, "deleteAll", TypeDescription.VOID);
    builder = defineMethod(builder, typeDescription, classLoader, "exists", new ForLoadedType(boolean.class), new ForLoadedType(Serializable.class));
    builder = defineMethod(builder, typeDescription, classLoader, "where", TargetType.resolve(new ForLoadedType(List.class), typeDescription), new ForLoadedType(Object[].class));
    builder = defineMethod(builder, typeDescription, classLoader, "where", TargetType.resolve(new ForLoadedType(List.class), typeDescription), new ForLoadedType(Filter.class));
    builder = defineMethod(builder, typeDescription, classLoader, "one", ForGenerifiedErasure.of(new ForLoadedType(Model.class)), new ForLoadedType(Object[].class));
    builder = defineMethod(builder, typeDescription, classLoader, "first", ForGenerifiedErasure.of(new ForLoadedType(Model.class)), new ForLoadedType(Object[].class));
    builder = defineMethod(builder, typeDescription, classLoader, "filter", new ForLoadedType(Filter.class));
    transformedClasses.add(typeDescription.getActualName());
    return builder;
}
 
Example #5
Source File: LocalVariables.java    From curiostack with MIT License 5 votes vote down vote up
/** Add a local variable with the specified {@code type}, referenceable by {@code handle}. */
Builder<T> add(Class<?> type, T handle) {
  int nextOffset = /* this */ 1 + accessors.size();
  TypeDefinition def = new ForLoadedType(type);
  accessors.put(handle, new VariableAccessor(MethodVariableAccess.of(def), nextOffset, def));
  frameLocalTypes.add(type);
  return this;
}
 
Example #6
Source File: DoWrite.java    From curiostack with MIT License 5 votes vote down vote up
private static StackManipulation unbox(ProtoFieldInfo field) {
  switch (field.valueJavaType()) {
    case INT:
    case ENUM:
      return new StackManipulation.Compound(
          TypeCasting.to(new ForLoadedType(Integer.class)), PrimitiveUnboxingDelegate.INTEGER);
    case LONG:
      return new StackManipulation.Compound(
          TypeCasting.to(new ForLoadedType(Long.class)), PrimitiveUnboxingDelegate.LONG);
    case BOOLEAN:
      return new StackManipulation.Compound(
          TypeCasting.to(new ForLoadedType(Boolean.class)), PrimitiveUnboxingDelegate.BOOLEAN);
    case FLOAT:
      return new StackManipulation.Compound(
          TypeCasting.to(new ForLoadedType(Float.class)), PrimitiveUnboxingDelegate.FLOAT);
    case DOUBLE:
      return new StackManipulation.Compound(
          TypeCasting.to(new ForLoadedType(Double.class)), PrimitiveUnboxingDelegate.DOUBLE);
    case STRING:
      return TypeCasting.to(new ForLoadedType(String.class));
    case BYTE_STRING:
      return TypeCasting.to(new ForLoadedType(ByteString.class));
    case MESSAGE:
      return TypeCasting.to(new ForLoadedType(Message.class));
    default:
      throw new IllegalStateException("Unknown field type.");
  }
}
 
Example #7
Source File: DoParse.java    From curiostack with MIT License 5 votes vote down vote up
/**
 * Returns the {@link StackManipulation} for setting the value of a field. This will be all the
 * elements for a repeated field.
 *
 * @param info description of the field to set.
 * @param beforeReadField jump target for before reading a field, used once this field is
 *     completed being set.
 * @param locals the method local variables
 * @param fieldsByName the instance fields
 */
private StackManipulation setFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  if (info.isMapField()) {
    return setMapFieldValue(info, beforeReadField, locals, fieldsByName);
  } else {
    final StackManipulation setConcreteValue = invoke(info.setValueMethod());
    final StackManipulation setSingleValue;
    if (info.valueJavaType() == JavaType.MESSAGE) {
      setSingleValue =
          new StackManipulation.Compound(
              TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
    } else if (info.valueType() == Type.ENUM && !info.isRepeated()) {
      // For non-repeated enums, we treat unknown as the default value.
      setSingleValue =
          new StackManipulation.Compound(ParseSupport_mapUnknownEnumValue, setConcreteValue);
    } else {
      setSingleValue = setConcreteValue;
    }
    if (info.descriptor().isRepeated()) {
      return setRepeatedFieldValue(info, beforeReadField, locals, fieldsByName, setSingleValue);
    } else {
      // Set a singular value, e.g.,
      // builder.setFoo(readValue());
      return new StackManipulation.Compound(
          locals.load(LocalVariable.builder),
          locals.load(LocalVariable.parser),
          readValue(info, fieldsByName, locals),
          setSingleValue,
          Removal.SINGLE,
          new Goto(beforeReadField));
    }
  }
}
 
Example #8
Source File: Controller.java    From Diorite with MIT License 5 votes vote down vote up
@Override
public void addClassData(Class<?> clazz)
{
    org.diorite.inject.impl.data.ClassData<Generic> classData = this.addClassData(new ForLoadedType(clazz));
    if (classData != null)
    {
        this.rebindSingleWithLock(classData);
    }
}
 
Example #9
Source File: Controller.java    From Diorite with MIT License 5 votes vote down vote up
@Override
protected ControllerClassData addClassData(TypeDescription typeDescription,
                                           org.diorite.inject.impl.data.ClassData<TypeDescription.ForLoadedType.Generic> classData)
{
    if (! (classData instanceof ControllerClassData))
    {
        throw new IllegalArgumentException("Unsupported class data for this controller");
    }
    this.map.put(typeDescription, classData);
    Lock lock = this.lock.writeLock();
    try
    {
        lock.lock();
        ((ControllerClassData) classData).setIndex(this.dataList.size());
        this.dataList.add(classData);
    }
    finally
    {
        lock.unlock();
    }
    try
    {
        ByteBuddyAgent.getInstrumentation().retransformClasses(AsmUtils.toClass(typeDescription));
    }
    catch (Exception e)
    {
        throw new TransformerError(e);
    }
    return (ControllerClassData) classData;
}
 
Example #10
Source File: Controller.java    From Diorite with MIT License 5 votes vote down vote up
private void rebindSingleWithLock(org.diorite.inject.impl.data.ClassData<TypeDescription.ForLoadedType.Generic> classData)
{
    Lock writeLock = this.lock.writeLock();
    try
    {
        writeLock.lock();
        this.rebindSingle(classData);
    }
    finally
    {
        writeLock.unlock();
    }
}
 
Example #11
Source File: Controller.java    From Diorite with MIT License 5 votes vote down vote up
private void rebindSingle(org.diorite.inject.impl.data.ClassData<TypeDescription.ForLoadedType.Generic> classData)
{
    Collection<org.diorite.inject.impl.data.InjectValueData<?, Generic>> allData = new ArrayList<>(100);
    for (org.diorite.inject.impl.data.MemberData<TypeDescription.ForLoadedType.Generic> fieldData : classData.getMembers())
    {
        allData.addAll(fieldData.getInjectValues());
    }
    for (org.diorite.inject.impl.data.InjectValueData<?, TypeDescription.ForLoadedType.Generic> valueData : allData)
    {
        this.findBinder(valueData);
    }
}
 
Example #12
Source File: Controller.java    From Diorite with MIT License 5 votes vote down vote up
@Override
public void rebind()
{
    Lock writeLock = this.lock.writeLock();
    try
    {
        writeLock.lock();
        for (org.diorite.inject.impl.data.ClassData<TypeDescription.ForLoadedType.Generic> classData : this.dataList)
        {
            this.rebindSingle(classData);
        }
        for (BinderValueData bindValue : this.bindValues)
        {
            Collection<? extends InjectValueData<?, ?>> injectValues = bindValue.getProvider().getInjectValues();
            if (injectValues.isEmpty())
            {
                continue;
            }
            for (InjectValueData<?, ?> valueData : injectValues)
            {
                this.findBinder((ControllerInjectValueData<?>) valueData);
            }
        }
    }
    finally
    {
        writeLock.unlock();
    }
}
 
Example #13
Source File: DoParse.java    From curiostack with MIT License 4 votes vote down vote up
/**
 * Returns the {@link StackManipulation} for setting the value of a map field.
 *
 * <p>Roughly equivalent to:
 *
 * <pre>{@code
 * ParseSupport.parseObjectStart(parser);
 * while (!ParseSupport.checkObjectEnd(parser.currentToken())) {
 *   builder.putFoo(readKey(), readValue());
 * }
 * }</pre>
 */
private StackManipulation setMapFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  final StackManipulation setConcreteValue = invoke(info.setValueMethod());
  final StackManipulation setMapEntry;
  if (info.valueJavaType() == JavaType.MESSAGE) {
    setMapEntry =
        new StackManipulation.Compound(
            TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
  } else {
    setMapEntry = setConcreteValue;
  }
  Label mapStart = new Label();
  Label afterSet = new Label();

  StackManipulation.Compound beforeReadKey =
      new StackManipulation.Compound(
          locals.load(LocalVariable.parser),
          ParseSupport_parseObjectStart,
          new SetJumpTargetLabel(mapStart),
          locals.load(LocalVariable.parser),
          Parser_currentToken,
          ParseSupport_checkObjectEnd,
          new IfTrue(beforeReadField));

  StackManipulation.Compound setValueAndPrepareForNext =
      new StackManipulation.Compound(
          setMapEntry,
          Removal.SINGLE,
          new SetJumpTargetLabel(afterSet),
          locals.load(LocalVariable.parser),
          Parser_nextToken,
          Removal.SINGLE,
          new Goto(mapStart));

  if (info.valueType() == Type.ENUM) {
    // We special-case enum since we may need to skip unknown values.
    final LocalVariable keyVar;
    switch (info.mapKeyField().valueJavaType()) {
      case INT:
        keyVar = LocalVariable.intMapKey;
        break;
      case LONG:
        keyVar = LocalVariable.longMapKey;
        break;
      case BOOLEAN:
        keyVar = LocalVariable.boolMapKey;
        break;
      case STRING:
        keyVar = LocalVariable.stringMapKey;
        break;
      default:
        throw new IllegalArgumentException("Invalid map key type");
    }

    return new StackManipulation.Compound(
        beforeReadKey,
        locals.load(LocalVariable.parser),
        readValue(info.mapKeyField(), fieldsByName, locals),
        locals.store(keyVar),
        locals.load(LocalVariable.parser),
        Parser_nextToken,
        Removal.SINGLE,
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        locals.store(LocalVariable.intvalue),
        locals.load(LocalVariable.intvalue),
        IntegerConstant.forValue(-1),
        new IfEqual(int.class, afterSet),
        locals.load(LocalVariable.builder),
        locals.load(keyVar),
        locals.load(LocalVariable.intvalue),
        setValueAndPrepareForNext);
  } else {
    return new StackManipulation.Compound(
        beforeReadKey,
        locals.load(LocalVariable.builder),
        locals.load(LocalVariable.parser),
        readValue(info.mapKeyField(), fieldsByName, locals),
        locals.load(LocalVariable.parser),
        Parser_nextToken,
        Removal.SINGLE,
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        setValueAndPrepareForNext);
  }
}
 
Example #14
Source File: Controller.java    From Diorite with MIT License 4 votes vote down vote up
@Override
protected ControllerClassData getClassData(Class<?> type)
{
    return (ControllerClassData) this.getClassData(new ForLoadedType(type));
}