Skip to content

Instantly share code, notes, and snippets.

@manzke
Last active December 23, 2015 18:39
Show Gist options
  • Save manzke/6677094 to your computer and use it in GitHub Desktop.
Save manzke/6677094 to your computer and use it in GitHub Desktop.
If you are often using TypeLiterals to describe your bindings of your generic classes, I find them quite ugly and the reference is to hard. That's why I have searched for a possibility to get a layer on top of it.
package de.devsurf.echo.frameworks.rs.service.startup.guice;
import java.lang.reflect.Type;
import com.google.inject.util.Types;
import de.devsurf.common.lang.build.Builder;
import de.devsurf.echo.frameworks.rs.system.api.TypeLiteralBuilder;
import de.devsurf.echo.frameworks.rs.system.api.TypeLiteralBuilder.RawTypeLiteralBuilder;
public class GuicyfiedLiterals implements TypeLiteralBuilder {
@Override
public GuicyfiedTypeLiteralBuilder fromRawType(Class<?> rawType) {
return new GuicyfiedTypeLiteralBuilder(rawType);
}
public class GuicyfiedTypeLiteralBuilder implements RawTypeLiteralBuilder, Builder<Type> {
private Type rawType;
private Type[] typeArguments;
private GuicyfiedTypeLiteralBuilder(Class<?> rawType) {
this.rawType = rawType;
}
@Override
public GuicyfiedTypeLiteralBuilder withType(Type... typeArguments) {
this.typeArguments = typeArguments;
return this;
}
@Override
public Type build() {
return Types.newParameterizedType(rawType, typeArguments);
}
}
}
package de.devsurf.echo.frameworks.rs.service.startup.guice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.AbstractModule;
import de.devsurf.echo.frameworks.rs.system.api.TypeLiteralBuilder;
public class GuicyfiedSystem extends AbstractModule {
private Logger logger = LoggerFactory.getLogger(GuicyfiedSystem.class);
@Override
public void configure() {
if (logger.isDebugEnabled()) {
logger.debug("configure()");
}
bind(TypeLiteralBuilder.class).to(GuicyfiedTypeLiteralBuilder.class);
}
}
package de.devsurf.echo.frameworks.rs.system.api;
import java.lang.reflect.Type;
import de.devsurf.common.lang.build.Builder;
public interface TypeLiteralBuilder {
public RawTypeLiteralBuilder fromRawType(Class<?> rawType);
public static interface RawTypeLiteralBuilder {
public Builder<Type> withType(Type... typeArguments);
}
}
@Inject
TypeLiteralBuilder literalBuilder;
Type type = literalBuilder.fromRawType(Converter.class)
.withType(ProviderEntity.class, Provider.class).build();
TypeLiteral<?> literal = TypeLiteral.get(type);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment