Search in sources :

Example 1 with TypeInfo

use of org.terasology.reflection.TypeInfo in project Terasology by MovingBlocks.

the class AssetTypeHandlerFactoryTest method testCreate.

@Test
public void testCreate() {
    TypeHandlerFactory factory = new AssetTypeHandlerFactory();
    List<TypeInfo<? extends Asset>> typesToTest = Lists.newArrayList(TypeInfo.of(Texture.class), TypeInfo.of(UIElement.class), TypeInfo.of(StaticSound.class), TypeInfo.of(StreamingSound.class));
    for (TypeInfo<? extends Asset> typeInfo : typesToTest) {
        Optional<? extends TypeHandler<? extends Asset>> typeHandler = factory.create(typeInfo, null);
        assertTrue(typeHandler.isPresent());
        assertTrue(typeHandler.get() instanceof AssetTypeHandler);
    }
}
Also used : UIElement(org.terasology.nui.asset.UIElement) StaticSound(org.terasology.engine.audio.StaticSound) AssetTypeHandler(org.terasology.engine.persistence.typeHandling.extensionTypes.AssetTypeHandler) Asset(org.terasology.gestalt.assets.Asset) TypeHandlerFactory(org.terasology.persistence.typeHandling.TypeHandlerFactory) StreamingSound(org.terasology.engine.audio.StreamingSound) TypeInfo(org.terasology.reflection.TypeInfo) Texture(org.terasology.engine.rendering.assets.texture.Texture) Test(org.junit.jupiter.api.Test)

Example 2 with TypeInfo

use of org.terasology.reflection.TypeInfo in project Terasology by MovingBlocks.

the class ObjectLayoutBuilder method populateConstructorParameters.

private void populateConstructorParameters(Binding<T> binding, ColumnLayout parameterLayout, UIButton createInstanceButton, Binding<Constructor<T>> selectedConstructor) {
    parameterLayout.removeAllWidgets();
    Parameter[] parameters = selectedConstructor.get().getParameters();
    List<TypeInfo<?>> parameterTypes = Arrays.stream(parameters).map(Parameter::getParameterizedType).map(parameterType -> ReflectionUtil.resolveType(type.getType(), parameterType)).map(TypeInfo::of).collect(Collectors.toList());
    List<Binding<?>> argumentBindings = parameterTypes.stream().map(parameterType -> new DefaultBinding<>(Defaults.defaultValue(parameterType.getRawType()))).collect(Collectors.toList());
    createInstanceButton.subscribe(widget -> {
        Object[] arguments = argumentBindings.stream().map(Binding::get).toArray();
        try {
            binding.set(selectedConstructor.get().newInstance(arguments));
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    });
    if (argumentBindings.isEmpty()) {
        // TODO: Translate
        parameterLayout.addWidget(new UILabel("Constructor has no parameters"));
        return;
    }
    ColumnLayout parametersExpandableLayout = WidgetUtil.createExpandableLayout(// TODO: Translate
    "Constructor Parameters", this::createDefaultLayout, layout -> {
        for (int i = 0; i < parameterTypes.size(); i++) {
            TypeInfo<?> parameterType = parameterTypes.get(i);
            Binding<?> argumentBinding = argumentBindings.get(i);
            Parameter parameter = parameters[i];
            Optional<UIWidget> optionalWidget = library.getBaseTypeWidget((Binding) argumentBinding, parameterType);
            if (!optionalWidget.isPresent()) {
                LOGGER.warn("Could not create widget for parameter of type {} of constructor {}", parameter, selectedConstructor.get());
                continue;
            }
            UIWidget widget = optionalWidget.get();
            String parameterLabelText = ReflectionUtil.typeToString(parameterType.getType(), true);
            layout.addWidget(WidgetUtil.labelize(widget, parameterLabelText, LABEL_WIDGET_ID));
        }
    }, this::createDefaultLayout);
    parameterLayout.addWidget(parametersExpandableLayout);
}
Also used : NotifyingBinding(org.terasology.nui.databinding.NotifyingBinding) DefaultBinding(org.terasology.nui.databinding.DefaultBinding) Binding(org.terasology.nui.databinding.Binding) Arrays(java.util.Arrays) Defaults(com.google.common.base.Defaults) LoggerFactory(org.slf4j.LoggerFactory) TypeWidgetLibrary(org.terasology.nui.widgets.types.TypeWidgetLibrary) TypeInfo(org.terasology.reflection.TypeInfo) ExpandableLayoutBuilder(org.terasology.nui.widgets.types.builtin.util.ExpandableLayoutBuilder) FieldsWidgetBuilder(org.terasology.nui.widgets.types.builtin.util.FieldsWidgetBuilder) WidgetUtil(org.terasology.nui.WidgetUtil) Constructor(java.lang.reflect.Constructor) UIBox(org.terasology.nui.widgets.UIBox) NotifyingBinding(org.terasology.nui.databinding.NotifyingBinding) DefaultBinding(org.terasology.nui.databinding.DefaultBinding) ColumnLayout(org.terasology.nui.layouts.ColumnLayout) Parameter(java.lang.reflect.Parameter) StringTextRenderer(org.terasology.nui.itemRendering.StringTextRenderer) Binding(org.terasology.nui.databinding.Binding) UIDropdownScrollable(org.terasology.nui.widgets.UIDropdownScrollable) Logger(org.slf4j.Logger) UILabel(org.terasology.nui.widgets.UILabel) ReflectionUtil(org.terasology.engine.utilities.ReflectionUtil) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) UIWidget(org.terasology.nui.UIWidget) List(java.util.List) UIButton(org.terasology.nui.widgets.UIButton) LABEL_WIDGET_ID(org.terasology.nui.widgets.types.TypeWidgetFactory.LABEL_WIDGET_ID) Optional(java.util.Optional) UILabel(org.terasology.nui.widgets.UILabel) DefaultBinding(org.terasology.nui.databinding.DefaultBinding) TypeInfo(org.terasology.reflection.TypeInfo) InvocationTargetException(java.lang.reflect.InvocationTargetException) UIWidget(org.terasology.nui.UIWidget) ColumnLayout(org.terasology.nui.layouts.ColumnLayout) Parameter(java.lang.reflect.Parameter)

Example 3 with TypeInfo

use of org.terasology.reflection.TypeInfo in project Terasology by MovingBlocks.

the class ReflectionUtilTest method testGetClassOfTypeWildcard.

@Test
public void testGetClassOfTypeWildcard() {
    class C<T> {
    }
    ParameterizedType cType = (ParameterizedType) new TypeInfo<C<?>>() {
    }.getType();
    Type wildcardType = cType.getActualTypeArguments()[0];
    assertEquals(Object.class, ReflectionUtil.getRawType(wildcardType));
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) GenericArrayType(java.lang.reflect.GenericArrayType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) WildcardType(java.lang.reflect.WildcardType) TypeInfo(org.terasology.reflection.TypeInfo) Test(org.junit.jupiter.api.Test)

Example 4 with TypeInfo

use of org.terasology.reflection.TypeInfo in project Terasology by MovingBlocks.

the class ReflectionUtilTest method testResolveWildcardType.

@Test
public void testResolveWildcardType() {
    class SomeClass<T, U> {

        private CopyStrategy<? extends T> t;

        private CopyStrategy<? super U> u;
    }
    TypeInfo<SomeClass<Float, Integer>> typeInfo = new TypeInfo<SomeClass<Float, Integer>>() {
    };
    ParameterizedType resolvedFieldType = (ParameterizedType) ReflectionUtil.resolveType(typeInfo.getType(), typeInfo.getRawType().getDeclaredFields()[0].getGenericType());
    WildcardType resolvedWildcardType = (WildcardType) resolvedFieldType.getActualTypeArguments()[0];
    assertEquals(Float.class, resolvedWildcardType.getUpperBounds()[0]);
    resolvedFieldType = (ParameterizedType) ReflectionUtil.resolveType(typeInfo.getType(), typeInfo.getRawType().getDeclaredFields()[1].getGenericType());
    resolvedWildcardType = (WildcardType) resolvedFieldType.getActualTypeArguments()[0];
    assertEquals(Integer.class, resolvedWildcardType.getLowerBounds()[0]);
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) WildcardType(java.lang.reflect.WildcardType) CopyStrategy(org.terasology.reflection.copy.CopyStrategy) TypeInfo(org.terasology.reflection.TypeInfo) Test(org.junit.jupiter.api.Test)

Example 5 with TypeInfo

use of org.terasology.reflection.TypeInfo in project Terasology by MovingBlocks.

the class RuntimeDelegatingTypeHandler method serializeNonNull.

@SuppressWarnings("unchecked")
@Override
public PersistedData serializeNonNull(T value, PersistedDataSerializer serializer) {
    // If primitive, don't go looking for the runtime type, serialize as is
    if (typeInfo.getRawType().isPrimitive() || Number.class.isAssignableFrom(typeInfo.getRawType())) {
        if (delegateHandler != null) {
            return delegateHandler.serialize(value, serializer);
        }
        LOGGER.error("Primitive '{}' does not have a TypeHandler", typeInfo);
        return serializer.serializeNull();
    }
    TypeHandler<T> chosenHandler = delegateHandler;
    Type runtimeType = getRuntimeTypeIfMoreSpecific(value);
    if (!typeInfo.getType().equals(runtimeType)) {
        Optional<TypeHandler<?>> runtimeTypeHandler = typeHandlerLibrary.getTypeHandler(runtimeType);
        chosenHandler = (TypeHandler<T>) runtimeTypeHandler.map(typeHandler -> {
            if (delegateHandler == null) {
                return typeHandler;
            }
            if (!(typeHandler instanceof ObjectFieldMapTypeHandler) && typeHandler.getClass().equals(delegateHandler.getClass())) {
                // use delegateHandler which might have more info
                return delegateHandler;
            }
            if (!isDefaultTypeHandler(typeHandler)) {
                // Custom handler for runtime type
                return typeHandler;
            }
            if (!isDefaultTypeHandler(delegateHandler)) {
                // Custom handler for specified type
                return delegateHandler;
            }
            return typeHandler;
        }).orElse(delegateHandler);
    }
    if (chosenHandler == null) {
        LOGGER.warn("Could not find appropriate TypeHandler for runtime type '{}', " + "serializing as base type '{}'", runtimeType, typeInfo);
        return serializeViaDelegate(value, serializer);
    }
    if (chosenHandler == delegateHandler) {
        return serializeViaDelegate(value, serializer);
    }
    Map<String, PersistedData> typeValuePersistedDataMap = Maps.newLinkedHashMap();
    Class<? extends T> subType = (Class<? extends T>) ReflectionUtil.getRawType(runtimeType);
    String subTypeIdentifier = sandbox.getSubTypeIdentifier(subType, typeInfo.getRawType());
    typeValuePersistedDataMap.put(TYPE_FIELD, serializer.serialize(subTypeIdentifier));
    PersistedData serialized = chosenHandler.serialize(value, serializer);
    // If the serialized representation is a Map, flatten it to include the class variable
    if (serialized.isValueMap()) {
        for (Map.Entry<String, PersistedData> entry : serialized.getAsValueMap().entrySet()) {
            typeValuePersistedDataMap.put(entry.getKey(), entry.getValue());
        }
    } else {
        typeValuePersistedDataMap.put(VALUE_FIELD, serialized);
    }
    return serializer.serialize(typeValuePersistedDataMap);
}
Also used : PersistedDataMap(org.terasology.persistence.typeHandling.PersistedDataMap) Logger(org.slf4j.Logger) ReflectionUtil(org.terasology.reflection.ReflectionUtil) LoggerFactory(org.slf4j.LoggerFactory) TypeInfo(org.terasology.reflection.TypeInfo) Set(java.util.Set) PersistedData(org.terasology.persistence.typeHandling.PersistedData) Maps(com.google.common.collect.Maps) TypeHandler(org.terasology.persistence.typeHandling.TypeHandler) PersistedDataSerializer(org.terasology.persistence.typeHandling.PersistedDataSerializer) TypeHandlerLibrary(org.terasology.persistence.typeHandling.TypeHandlerLibrary) Type(java.lang.reflect.Type) TypeHandlerContext(org.terasology.persistence.typeHandling.TypeHandlerContext) Map(java.util.Map) Optional(java.util.Optional) SerializationSandbox(org.terasology.persistence.typeHandling.reflection.SerializationSandbox) Type(java.lang.reflect.Type) PersistedData(org.terasology.persistence.typeHandling.PersistedData) TypeHandler(org.terasology.persistence.typeHandling.TypeHandler) PersistedDataMap(org.terasology.persistence.typeHandling.PersistedDataMap) Map(java.util.Map)

Aggregations

TypeInfo (org.terasology.reflection.TypeInfo)19 Test (org.junit.jupiter.api.Test)11 Type (java.lang.reflect.Type)10 ParameterizedType (java.lang.reflect.ParameterizedType)9 GenericArrayType (java.lang.reflect.GenericArrayType)8 WildcardType (java.lang.reflect.WildcardType)8 Optional (java.util.Optional)4 Set (java.util.Set)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 Map (java.util.Map)3 Collectors (java.util.stream.Collectors)3 CopyStrategy (org.terasology.reflection.copy.CopyStrategy)3 ImmutableSet (com.google.common.collect.ImmutableSet)2 Constructor (java.lang.reflect.Constructor)2 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 HashMap (java.util.HashMap)2 List (java.util.List)2