[SalesForce] Can you use generics in Apex

While researching the possibility of using generics in apex I can across a blog with this:

"Generics are partially supported in Apex, you must be using them with
Collections and Batch Apex."

However, I couldn't really find any more information on that. Can generics be used in apex? What are the limitations?

By generic I mean in a "generic programming" sense where types are not defined in code but determined at run time. For example, I would like to be able to write a List iterator in apex but not have to define the object type. Something like:

global class ListIterator implements Iterator<T>{
  global boolean hasNext(){ 
    ...
  }    

  global T next(){        
    ...
  } 
}

Where T would be defined at runtime – it could be Account, or Opportunity, or CustomObject1 or CustomClassX. Not only would it work with these data types but when I call hasNext() it would return an instance of that class (as opposed to returning a generic Object or sObject that I would then have to cast).

Best Answer

NOTE: This answer is not useful for any code saved in v26.0 or later.

See Winter '13 Release Notes pg. 191 (193 of the PDF)

Take a look at the Parameterized Typing and Interfaces section in the Apex Developer's Guide. This is what you are looking for, I'm pretty sure.

The other way that Generics are commonly used in Apex are what you stated which is in the Collections and Batch Apex classes.

For example, without generics you'd have something like:

List contacts = new List();
contacts.add(new Contact());
contacts.add(new Account());  // uh oh.

With generics you have the compile time type safety:

List<Contact> contacts = new List<Contact>();
contacts.add(new Contact());
contacts.add(new Account()); // won't save/compile because the list knows it only has Contacts.

So, in theory there's some generic code somewhere in the Apex system that handles all of the List work such as:

public class List<T> {
    public void add(T element) { 
      // do the magic
    }
    public T get(Integer index) {
      // do the magic
    }
}
Related Topic