Generify class and method

To generify a class, declare the type directly after the class name:

public class NaturalNumber<T extends Integer> {

    private T n;

    public NaturalNumber(T n)  { this.n = n; }

    public boolean isEven() {
        return n.intValue() % 2 == 0;
    }

    // ...
}

To Generify a method signature (return type), declare the class access modifier:

    
    public static <T extends Status> Status getStatusByInternalLabel(Class<T> c, String internalLabel){
        if(!c.isEnum() || internalLabel == null){
            return null;
        }
        Status result = null;
        Object[] objects = c.getEnumConstants();
        for (Object o : objects){
            if(internalLabel.equals(((Status)o).getInternalLabel())){
                 result = (Status)o;
            }
        }
        return result;
    }

To Generify a method parameter, declare before the parameter:

    public static  List statusEnumsInternalLabelToSortedList(Class<? extends Status> c){
        if(!c.isEnum()){
            return null;
        }
        Object[] objects = c.getEnumConstants();
        List result = new ArrayList();
        for (Object o : objects){
            result.add(((Status)o).getInternalLabel());
        }
        Collections.sort(result);
        return result;
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s