I would like to ask what's the difference between
bindConstant().annotatedWith(Names.named("keepAliveInterval")).to(60);
and
bind(Integer.TYPE).annotatedWith(Names.named("keepAliveInterval")).toInstance(60);
I would like to load all my configuration properties with Names.bindProperties(binder(), prop); in my module and I discovered that it uses the latter one for binding properties.
Thanks, regards
Marek
I think reasons to use bindConstant() are:
It requires that you use an annotated binding. You can't do bindConstant().to(foo). Since the types you bind with it are primitives and Strings, it's unlikely that an annotation-less binding would make sense for any of them.
It requires less effort since you don't have to specify the type (by the way, bindConstant() binds an int to Integer.class rather than Integer.TYPE, not sure if that matters).
I think Names.bindProperties doesn't use bindConstant just because it's internal code and a little more code is OK to skip a step or two in the process of making a binding. In your own modules, I'd just use bindConstant because it's easy and more clear.
bindConstant() has the benefit of being able to set different primitives because of predefined TypeConverter instances within Guice itself.
Take the following binding definition as an example:
bindContant().annotatedWith(#Names.named("c")).to("30");
Then in a class where you want the injection:
#Inject #Named("c") int value;
Guice will convert the bound String into an int for you. If it cannot, it will say so.
The benefit of bindConstant() is the type conversion that can happen. Explicitly binding an int does not give you that luxury.
Related
I'm reading java language specifications (JLS): annotations
An annotation denotes a specific invocation of an annotation type
(ยง9.6)
And in 9.6:
An annotation type declaration specifies a new annotation type, a
special kind of interface type.
So e.g. #annotation1 should invoke annotation type annotation1. I could not find info what it means by web search or questions here. All I've found only about invocations of methods of interfaces, not interface types. I've read what some build-in annotations do of cause, e.g. infamous #Override, however I want clear knowledge preferably with links to JLS what interface type invocation is as I've read annotations are used by many useful frameworks which I want to use efficiently.
If you write #SomeAnnotation you basically create in instance of that annotation type (there might be some caching but I'm not aware of this). This becomes especially apparent when an annotation has data, e.g. #SomeAnnotation(name="Alexei"). In that case you could get the annotation instance of type SomeAnnotation and then invoke name() on it to get the value "Alexei").
I've read annotations are used by many useful frameworks which I want to use efficiently.
Most frameworks use reflection to inspect your classes and collect information on the annotations, e.g. via Class.getAnnotation(SomeAnnotation.class) and many other similar methods. That information is then used to do whatever the framework needs them for, e.g. CDI would use the scope annotations to build its internal bean repository.
To use those frameworks you don't have to know about the specifics of how they use the annotations or what invocation actually means. Just use the annotations themselves as the framework requires you to do.
If you want to develop your own framework then you might need some more information, especially on the reflection capabilities.
As far as my understanding of the link jls you posted, annotations types are special interface types and one should not think that invocation in that context means same invocation as say for a method. Compiler inserts markers with code and they can be used later (or right during compilation as with #override) .
Can I have one setSource() setter with two versions for two different argument types, i.e. setSource(InputStream) and setSource(TargetDataLine)?
Internally I hold the value in Object field and dispatch processing based on RTTI, but I wonder if bean-realted libraries like Spring will accept such setters gracefully? I.e. will I able to put values of different types into one source bean field?
This doesn't really seem right. What does getSource() return ? An Object ? If so, I'd suggest that your setSource() accepts an Object.
Obviously that seems too 'generic', and I wonder if this problem indicates that your modelling is incorrect, and that you need two specialised subclasses handling different source types.
Failing that, why not be explicit and have setStreamSource() / setTargetDataLineSource() with the correct types, and enforce the setting of one or the other, but not both (I still think the specialisation is the way to go, however).
Please provide some basic information of how TypeLiteral in Google Guice or Java EE is used, It will be very helpful if it would be explained using a simple code, thanks in advance
The purpose of TypeLiteral in Guice is to allow you to bind classes and instances to generic types (with type parameters specified) avoiding the problems stemming from the fact that generics are not reified in Java, i.e. from the fact that erasure hides the difference between SomeInterface<String> and SomeInterface<Integer> at runtime. TypeLiteral allows the value of a generic parameter survive erasure by creating an ad hoc subclass of the generic type.
Example usage of TypeLiteral:
bind(new TypeLiteral<SomeInterface<String>>(){})
.to(SomeImplementation.class);
This binds a parameter of type SomeInterface<String> to SomeImplementation class.
For some background information have a look at this blog post on super type tokens and then this one on type literals.
Like anything in Guice - modularity, reusability, and removal of boilerplate are core concepts of all utilities.
Of course, anything you do in Guice can be mimicked in Java - at the cost of lots of boilerplate So... the real question is :
How can we USE TypeLiterals to write more modular/reusable components ?
The power of TypeLiterals in Guice is that it allows you to refernce implementations of a service without defining what that service is.
Lets start with a simple list in a program where we have many types of lists that are processed differntly :
List<String> myStringList = new ArrayList<String>();
Now, how should I process these Strings ? At runtime, there is no way to "know" that its a String list. So, often times I might create a factory, like so , that gets processing objects for me :
ProcessorFactory.get(String.class).process(myStringList);
Thus, I might use a factory (with a bunch of if/else or case statements) to define processors for different data types. My constructor, for the object which uses these processors, and which needs access to various Processor Implementations, might look like this :
public MyClass(Processor<String> strProcessor, Processor<Integer> intProcessor)P
{
//Simple enough, but alot of boiler plate is required to launch this constructor.
}
//and to invoke
new MyClass(PRocessorFactory.get(....), ProcessorFactory.get(...));
All good so far... Until we realize that there is a better way :
In the Guice world, I can forget about writing this factory - rather, I can explicitly BIND classes to processors. The advantage of this is that there are no static dependencies - the class which needs to USE processor implementations DOES NOT need any static dependency on a factory -rather, the classes are directly injected. Thus, I can easily define a class which uses complex dependencies, without having to build a factory aware class builder... Thus, I have far less boilerplate :
#Inject
public MyClass(Processor<String> implStr, Processor<Integer> implInt)
{
//Now , this method will work magically, because Guice is capable of
//Using the loaded modules, which define bindings between generics and their implementations
}
//Elsewhere I simply define a single guice module that does the binding, and make sure to load it before my application launches.
There is a good tutorial on this with interface implementations and binding examples, here : http://thejavablog.wordpress.com/2008/11/17/how-to-inject-a-generic-interface-using-guice/
This is a way how guys bypass generics erasure in java. You need it, when you want ot bind some implementation to parametrized(generic) interface. Found some usage in Guice docs:
bind(new TypeLiteral<PaymentService<CreditCard>>() {})
.to(CreditCardPaymentService.class);
This admittedly odd construct is the way to bind a parameterized type. It tells Guice how to honor an injection request for an element of type PaymentService. The class CreditCardPaymentService must implement the PaymentService interface. Guice cannot currently bind or inject a generic type, such as Set; all type parameters must be fully specified.
The TypeLiteral class is a workaround for the fact that you cannot have class literals for generic types. The API doc of Binder (this is from Google Guice, but the Java EE class of the same name has exactly the same purpose) gives an example for how it's used:
bind(new TypeLiteral<PaymentService<CreditCard>>() {})
.to(CreditCardPaymentService.class);
This specifies that any auto-injected reference of type PaymentService<CreditCard> will be implemented by the concrete class CreditCardPaymentService, leaving the option for PaymentService<Coupon> to be implemented by a different class. Without TypeLiteral, this would not be possible because the Java compiler will accept PaymentService<CreditCard>.class, only PaymentService.class.
Note that this also requires the use of anonymous subclasses (the {} after new TypeLiteral<PaymentService<CreditCard>>()) in order to work around type erasure.
I'll simplify the answer/reason for the existence of TypeLiteral<> in GUICE:
if java allows you to write:
bind(FooInterface<String>.class).to(FooImplementation.class);
then you are done, there is no need for TypeLiteral<>
but java has this "Type Erasure" thing for generics, so FooInterface<String>.class won't even get complied.
So you use:
bind(new TypeLiteral<FooInterface<String>>() {}).to(FooImplementation.class);
"new TypeLiteral<Interface>() {}" will create some anonymous class and new an object out of it. You can imagine that object knows everything about the tpye info of the Interface, so GUICE use that object to perform the DI magic.
which one of below is better or to be prefered
new Object();
Object.setValue1("1");
Object.setValue2("2");
Object.setValue3("3");
or
new Object("1","2","3");
(I assume you're talking about the design of your own classes, rather than how to use other already-designed classes.)
Neither is always "better," it depends on the nature of the object and (to an extent) on your preferred style.
If an object cannot have a meaningful state without some external information, then requiring that information in the constructor makes sense, because then you can't create instances with an invalid state.
However, having constructors that require as little information as possible is useful in terms of making the class easy to use in a variety of situations. If the class is such that a zero-arguments constructor is feasible and doesn't complicate the class, it's great in terms of supporting various use-cases, including cases where the instance is being built as part of parsing some other structure (JSON, XML, etc.).
There is also a third option that builds on the use of fluent interfaces
MyObject obj = new MyObject().setValue1("1").setValue("2").setValue("3");
I personally like this approach but if the number of parameters is short and known at the time of construction AND the varying possible combinations of parameters is short then I would take the route of parameters on the constructor. I think most would agree that 12 constructor overloads are an eye sore.
Depends on whether you know the values at the time of object construction.
If Yes, then use the constructor version if not then you will have to use the other version.
Ofcourse,Initialization through the Constructor version is faster because it involves just one function call over 3 set function calls and also it is more logical way.
Its always better performance to call in constructor If you know values already.
Then there is my preferred alternative. Thing is the name of some interface. It creates an anonymous class.
Thing createThing ( final int val1 , final int val2 , final int val3 )
{
return new Thing ( )
{
// can use val1, val2, val3
} ;
}
It all depends on the application.
Calling Parameterized constructor will be a good idea if at Compile time you know what values to be given to your variables, rather than calling Setters. Because you are calling 3 setter methods and in parameterized constructor, you are just passing to the cnostructor it self.
But if at compile time you don't know what values to be given then how can you call paramterized constructor.
But for initialization it will be better to call parameterized constructor.
There is a semantic difference. If (1) you are instantiating an object with an initial state. In (2) you are changing the state of an existing instance (3 times). It's a small difference but may become very important in more complex systems (especially if you rely on various JavaBean conventions). But still, neither one is wrong or better.
Suppose, I have a lot of classes, which are constructed using Java reflection (for some reason). Now I need to post-inject values to fields, which are
annotated with #PostInject.
public class SomeClass {
#PostInject
private final String someString = null;
public void someMethod() {
// here, someString has a value.
}
}
My question is: what is a fast way to set a field using reflection?
Remember, I need to do this very often on a lot of classes, that's
why performance is relevant.
What I would do by intuition is shown by this pseudo-code:
get all fields of the class
clazz.getFields();
check, which are annotated with #PostInject
eachField.getAnnotation(PostInject.class);
make these fields accessible
eachAnnotatedField.setAccessible(true);
set them to a certain value
eachAnnotatedField.set(clazz, someValue);
I'm afraid that getting all fields is the slowest thing to do.
Can I someone get a field, when I know it from the beginning?
NOTE: I can't just let the classes implement some interface, which would
allow to set the fields using a method. I need POJOs.
NOTE2: Why I want post-field injection: From the point of view of an API user, it must be possible to use final fields. Furthermore, when the types and number of fields are not known by the API a priori, it is impossible to achieve field initialization using an interface.
NOTE2b: From the point of view of the user, the final contract is not broken. It stays final. First, a field gets initialized, then it can't be changed. By the way: there are a lot of APIs which use this concept, one of them is JAXB (part of the JDK).
How about doing steps 1 to 3 just after you constructed the object and saving the set of annotated fields that you obtain either in the object itself or by keeping a separate map of class to set-of-annotated-fields?
Then, when you need to update the injected fields in an object, retrieve the set from either the object or the seperate map and perform step 4.
Don't know if it's any good, but this project looks like it would do what you want. Quote:
A set of reflection utilities and
miscellaneous utilities related to
working with classes and their fields
with no dependencies which is
compatible with java 1.5 and generics.
The utilities cache reflection data
for high performance operation but
uses weak/soft caching to avoid
holding open ClassLoaders and causing
the caches to exist in memory
permanently. The ability to override
the caching mechanism with your own is
supported.
Another option, as you say you know the few fields concerned from the beginning, is to ask only for those fields or methods.
Example : see getDeclaredMethod or getDeclaredField in java/lang/Class.html
You can exploit existing frameworks that allow to inject dependencies on object construction. For example Spring allows to do that with aspectj weaving. The general idea is that you define bean dependencies at spring level and just mark target classes in order to advise their object creation. Actual dependency resolution logic is injected directly to the class byte-code (it's possible to use either compile- or load-time weaving).
Fastest way to do anything with reflection is to cache the actual Reflection API classes whenever possible. For example I very recently made a yet-another-dynamic-POJO-manipulator which I believe is one of those things everyone ends up doing at some point which enables me to do this:
Object o = ...
BeanPropertyController c = BeanPropertyController.of(o);
for (String propertyName : c.getPropertyNames()) {
if (c.access(propertyName) == null &&
c.typeOf(propertyName).equals(String.class)) {
c.mutate(propertyName, "");
}
}
The way it works is that it basically has that one controller object which lazyloads all the properties of the bean (note: some magic involved) and then reuses them as long as the actual controller object is alive. All I can say is that by just saving the Method objects themselves I managed to turn that thing into a damn fast thing and I'm quite proud of it and even considering releasing it assuming I can manage to sort out copyrights etc.