Use of TypeLiteral in java - java

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.

Related

Why does Java's Dynamic Proxies need reflection?

Java's Dynamic Proxy Docs describe these constructors as the following:
A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class.
Now, while everything in this sentence is accurate. All of this information is in fact present at compile time. In Java, when you are creating a proxy, you specify the exact interface you want to proxy in your code.
Now the first thing that really confuses me, is why the byte code here needs to be generated at run time? All of this information is present at the compile time... (and you don't even have to deal with type erasure)
P.S: I am not sure if this is still the case, basing this on a quite dated accepted answer here: How does Java's Dynamic Proxy actually work?)
The next step in getting this work is the type checking/type inference. I am not sure how Java actually handles this, but you need to be able to use Proxy<A> interchangeably with A. In order to pull this of you need the following:
โˆ€ method m โˆˆ A, m โˆˆ Proxy<A>
Which means that
you need your proxy to have the same structure
you need some kind of delegation (i.e. dynamic dispatch).
Once you start writing out the inference rules, this gives us something very familiar. Structural Typing
Now Java doesn't have structural typing but one could easily add the few inference rules (i.e. Typescript) especially given Java has boxed primitives (Scala for example doesn't which makes it very difficult to introduce structural inference).
The Actual Question
Reflection is hard, not safe and not super performant. My question is why and how Java's proxies use reflection? It seems like most of this functionality could be implemented using other features already present in the language.

java: what does it mean to invoke interface type?

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) .

Programming to an interface instead of an implementation: Why is assigning the concrete implementation of an object at runtime even better?

In Head First Design Patterns, it was mentioned that you should code to an interface instead of an implementation however the last part of the code example got me confused. How is assigning the concrete implementation of an object at runtime a better design?
Does it mean that its better to put the instantation of the objects within a method in the class that uses the supertype? (a method whose purpose is specifically returning an object to a variable of the superclass)
//Programming to an implementation would be:
Dog d = new Dog();
d.bark();
//Programming to an interface/supertype would be:
Animal animal = new Dog();
animal.makeSound();
//Even better is assigning the concrete implementation at runtime: (says the book)
a = getAnimal();
animal.makeSound();
Even better way is to get the concrete class figured by someone else depending on the environment/context of your code execution. This is called Inversion of control/ dependency injection where the actual class is either configured in some configuration files or coding by convention is used to identify the correct file.
Coming back to why,imagine a project of moderate complexity where you have to talk to a DB. If you hard code the way to access a DB , you will end up asking customers to stick to a particular type/version of the DB. This is how JDBC works. Similarly for more complex scenarios, imagine moving from Db based system file based. Once you get that software should be designed for flexibility, its easy to appreciate the delayed initialisation of concrete classes.
If I were to say why in one word, then it would be: Centralization.
What I mean by this, is that you assign those concrete types at the start of your application somewhere in a single place and provide them to the classes that need them as interfaces, so those classes don't get coupled to the concrete types themselves but rather rely on those abstractions or interfaces.
This is similar to using the Factory pattern, so you don't spread object creation through out the program but rather in a single spot, which is easy to modify in the future.
This also enables you to use Dependency Injection and Inversion of Control which in turn comes with a bunch of good stuff like better testing, maintainability, run-time configuration, etc .

My confusion: reflection in Java

I've just finished reading the chapter of 'Thinking in Java' concerning type information and reflection. While instanceof seems quite natural to me, some examples of reflection made me confused. I want to know if reflection is widely used in Java projects? What are 'the good parts' of reflection? Can you suggest any interesting lectures about reflection and type information with more good and worthy examples?
Edit (one more question):
Why is it useful to access private methods and fields withjava.lang.reflect.Method.setAccesible()?
Thanks in advance.
if you could post some of the examples I would be glad to explain it for you.
Reflection is wildly used with frameworks that need to extract meta-info about the running object (e.g. frameworks which depends on Annotations or the fields in your objets, think about Hibernate, Spring and a lot others).
On a higher layer, I sometimes use reflection to provide generic functionality (e.g. to encode every String in an object, emulate Duck Typing and such).
I know that you already read a book which covers the basics about reflection, but I need to point Sun (erm.. Oracle) official Tutorial as a must read: http://download.oracle.com/javase/tutorial/reflect/
One good example in my opinion is instantiating objects based on class names that are known only at runtime, for example contained in a configuration file.
You will still need to know a common interface to the classes you're dynamically instantiating, so you have something to cast them too. But this lets a configuration drive which implementation will be used.
Another example could be when you have to cast an object to a class that it's a descendant. If you are not sure about the type of that object, you can use instanceof to assure that the cast will be correct at runtime avoiding a class cast exception.
An example:
public void actionPerformed (ActionEvent e){
Object obj = e.getSource();
if (obj instanceof objType)
objType t = (objType) obj; // you can check the type using instanceof if you are not sure about obj class at runtime
}
The reason to provide such features in Reflection is due to multiple situations where tool/application needs meta information of class, variables, methods. For example:-
IDEs using auto completion functionality to get method names and attribute names.
Tomcat web container to forward the request to correct module by parsing their web.xml files and request URI.
JUnit uses reflection to enumerate all methods in a class; assuming either testXXX named methods as test methods or methods annoted by #Test.
To read full article about reflection you can check http://modernpathshala.com/Forum/Thread/Interview/308/give-some-examples-where-reflection-is-used

What's the conception behind: Type - Element - Mirror

I'm working with Java 6's annotation processing, i.e. what can be found within javax.annotation.processing (not Java 5's APT).
I wonder what the conceptional difference between the various Element, Type, and Mirror classes is. As I don't really understand this, it's hard to efficiently program an annotation processor. There are various methods that 'convert' between these notions but I'm not really sure what I'm doing when using them.
So, for example, let me have an instance of AnnotationMirror.
When I call getAnnotationType() I get an instance of DeclaredType (which implements TypeMirror for whatever reason).
Then I can call asElement() on this one and obtain an instance of Element.
What has happened?
There is indeed on overlap between these concepts.
Element models the static structure of the program, ie packages, classes, methods and variables. Just think of all you see in the package explorer of Eclipse.
Type models the statically defined type constraints of the program, ie types, generic type parameters, generic type wildcards. Just think of everything that is part of Java's type declarations.
Mirror is an alternative concept to reflection by Gilad Bracha and Dave Ungar initially developed for Self, a prototype-based Smalltalk dialect. The basic idea is to separate queries about the structure of code (and also runtime manipulation of the structure, alas not available in Java) from the domain objects. So to query an object about its methods, instead of calling #getClass you would ask the system for a mirror through which you can see the reflection of the object. Thanks to that separation you can also mirror on classes that are not loaded (as is the case during annotation processing) or even classes in a remote image. For example V8 (Google's Javascript engine) uses mirrors for debugging Javascript code that runs in another object space.
This paper may help understanding the design of Java 6 annotation processing:
Gilad Bracha and David Ungar. Mirrors:
Design Principles for Meta-level
Facilities of Object-Oriented
Programming Languages. In Proc. of
the ACM Conf. on Object-Oriented
Programming, Systems, Languages and
Applications, October 2004.
The object of type javax.lang.model.element.AnnotationMirror represents an annotation in your code.
The declared type represents the annotation class.
Its element is the generic class (see http://java.sun.com/javase/6/docs/api/javax/lang/model/element/TypeElement.html for more information on that matter). The element might be the generic version of a class, like List, where as the declared type is the parametrized version, for instance List<String>. However I'm not sure it is possible to have annotations classes use generics and thus the distinction might be irrelevant in that context.
For instance lets say you have the following JUnit4 method:
#Test(expected = MyException.class)
public void myTest() {
// do some tests on some class...
}
The AnnotationMirror represents #Test(expected = NullPointerException.class). The declared type is the org.junit.Test class. The element is more or less the same as there are no generics involved.

Categories

Resources