Summary of usage of Java return type generics
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The basic usage of Java generics is not much to say, mainly a compile-time check, but also to avoid the coercion in our code, compared to the classic usage of generic DAO, generic page dto.
Now I want to say is a very interesting but seems not too many people in the code to use the method, the previous period of time with guava and op4j when the use of this, look at the source code, is also very simple.
For example, the method of creating a collection in guava list<xx> list = Lists.newarraylist (), which replaces our traditional new arraylist<xx>, why we do not need a generic on the right side of =, we look at the source code.
[Java]View PlainCopy
- Public static <E> arraylist<e> newarraylist () {
- return new arraylist<e> ();
- }
The return type has a generic e in it, and the source of the generic is between static and ArrayList, and my own understanding is that this is the same as = left side, which may not be professional but that's what it means.
So I leaf out in my own code.
What I'm going to do is a copy of the httpsession mechanism of the custom protocol is session. The Httpsession.getattribute method returns an object, and then we type the conversion. Now I use the return type generics to refine this code, and here is the code for the getattribute of my custom protocol session.
[Java]View PlainCopy
- @SuppressWarnings ("unchecked")
- Public <E> E getattribute (String key) {
- return (E) map.get (key);
- }
Calling code
[Java]View PlainCopy
- Boolean IsFirst = Session.getattribute ("first");
We're going to write this in httpsession.
[Java]View PlainCopy
- Boolean IsFirst = (Boolean) Session.getattribute ("first");
There's a lot more to be used in generics, and there are new additions and updates.
Summary of usage of Java return type generics