Help with generics
I've been working with Java for years, but I'm new to generics. Can you help me translate this code to plain English?
publicinterface GenericDAO<T, IDextends Serializable>{
T findById(ID id,boolean lock);
List<T> findAll();
}
Thanks!
Paul C.
Sr. Developer
www.jbilling.com - The open source enterprise billing system
> I've been working with Java for years, but I'm new to
> generics. Can you help me translate this code to
> plain English?
>
> > public interface GenericDAO<T, ID extends
> Serializable> {
>
>T findById(ID id, boolean lock);
>List<T> findAll();
> }
>
>
> Thanks!
>
> Paul C.
> Sr. Developer
> www.jbilling.com - The open source enterprise billing
> system
this is an interface called GenericDAO, and it is designed to work with types T and ID (bear with me on that). T and ID are what's known as type tokens, when you instantiate any class that implements this, you provide actual types in lieu of those tokens: whatever type you provide in place of T, the findById method will return instances of that type, and findAll will return a List of that type. the findById method takes in an instance of whatever you substitute for ID. note that whatever type you give for ID must impement Serializable. an example:
public class MyDAO implements GenericDAO<Customer, Long> {
public Customer findById(Long id, boolean lock) {
//actual work here
}
public List<Customer> findAll() {
//actual work here
}
}
it's a means of getting more compile-time type safety. partially in existence to avoid having collections containing just objects, and all the bothersome casting that goes with it. you can now declare a List, or a Set or a Map to be of one specific type, or related types, and not have to worry about putting the wrong type in by mistake - sort-of: generics are only present at compile-time, back in the JVM you're still dealing with Objects, but the compiler has filled in the blanks of casting for you
there's plenty of good material on the 'net about this where you'll doubtless find a much better explaination than I just gave you, but hopefully you've got a vague idea now
> > T and ID are what's known as type tokens> > They are called type variables. A type token> something different which> is also known as a class literal, for example,> String.class.really? sorry, my mistake! cheers, peter