Does apex support generics?

You want to use Object as a generic class to use. Also, no need to check null AND an empty string (it'll always be null or a non-empty string). Here's the modifications you want:

public class Criteria {
   public String FieldName; 
   public String Operator;      
   public Object FieldValue;
   public Criteria(String f_name, Object f_value) {
       FieldName = f_name;
       FieldValue = f_value;
       Operator = '=';
   }
   public String getSOQLCriteria() {
       if(FieldValue instanceOf String) {
           return FieldName + Operator + String.escapeSingleQuotes(String.valueOf(FieldValue));
       }
       return FieldName + Operator + FieldValue;
   }
   public String IsFieldValueGiven() {
       return FieldValue != null;
   }
}

The actual getSOQLCriteria method would need to check the data type of the field value to determine the appropriate method to use. The above method should work for all primitive data types.


In Apex, the best you can do is change the parameter on your constructor to have the generic Object type.

If you need to process the values in a particular way based on type, you can use the instanceof keyword to determine what type of data got passed in, but in general though, the String.valueOf() method is a good catch-all.

class

  1 public class MyClass{
  2 
  3     String s;
  4 
  5     public MyClass(Object o){
  6        s = String.valueOf(o);
  7     }
  8 }

anonymous block

  2 system.debug(new MyClass('53'));
  3 system.debug(new MyClass(53));
  4 system.debug(new MyClass(53.3));
  5 system.debug(new MyClass(System.today()));
  6 system.debug(new MyClass(new Account(Name='My Account')));

debug log

09:37:20.86 (92471396)|USER_DEBUG|[2]|DEBUG|MyClass:[s=53]
09:37:20.86 (92535244)|USER_DEBUG|[3]|DEBUG|MyClass:[s=53]
09:37:20.86 (92598190)|USER_DEBUG|[4]|DEBUG|MyClass:[s=53.3]
09:37:20.86 (92651329)|USER_DEBUG|[5]|DEBUG|MyClass:[s=2017-07-21 00:00:00]
09:37:20.86 (92858629)|USER_DEBUG|[6]|DEBUG|MyClass:[s=Account:{Name=My Account}]

From the Apex documentation on String methods:

public static String valueOf(Object toConvert)

If the argument is not a String, the valueOf method converts it into a String by calling the toString method on the argument, if available, or any overridden toString method if the argument is a user-defined type. Otherwise, if no toString method is available, it returns a String representation of the argument.

I haven't been able to track down how exactly this method "returns a String representation of the argument" when there is no toString() method available, but despite the lack of visibility into the internals, this method is very handy.

Tags:

Generics

Apex