2

I am developing a generic utility which should have minimum size and code duplication. Is this code good or bad java practise?

 public static <T> T getProperty(String fileName,String propertyName, Class<T> type ){
    T result=null;
    try{
        Properties properties=propertyMap.get(fileName);
        if(type.getName().equals("java.lang.Float")){
            result=type.cast(java.lang.Float.valueOf(properties.getProperty(propertyName)));
        }else if(type.getName().equals("java.lang.Long")){
            result=type.cast(java.lang.Long.valueOf(properties.getProperty(propertyName)));
        }else if(type.getName().equals("java.lang.String")){
            result=type.cast(java.lang.String.valueOf(properties.getProperty(propertyName)));
        }else if(type.getName().equals("java.lang.Double")){
            result=type.cast(java.lang.Double.valueOf(properties.getProperty(propertyName)));
        }else if(type.getName().equals("java.lang.Integer")){
            result=type.cast(java.lang.Integer.valueOf(properties.getProperty(propertyName)));
        }
    }catch(ClassCastException e){
        logger.error(CommonUtils.getExceptionTrace(e));
    }catch(NullPointerException e){
        logger.error(CommonUtils.getExceptionTrace(e));
    }catch(Exception e){
        logger.error(CommonUtils.getExceptionTrace(e));
    }
    return result;
}
1
  • 1
    You should not catch any RuntimeExceptions Commented Apr 2, 2014 at 9:13

1 Answer 1

1

Your code seems to be a reasonable use of generics within Java. It can be simplified a little, as shown below.

Note: for testing reasons I adjusting your example to simply parse a string rather than reading a property file. It should be clear how to undo those changes:

public static <T> T getProperty(String input, Class<T> type) {

  try {
    if (type.equals(Float.class)) {
      return type.cast(Float.valueOf(input));
    } else if (type.equals(Long.class)) {
      return type.cast(Long.valueOf(input));
    } else if (type.equals(String.class)) {
      return type.cast(String.valueOf(input));
    } else if (type.equals(Double.class)) {
      return type.cast(Double.valueOf(input));
    } else if (type.equals(Integer.class)) {
      return type.cast(Integer.valueOf(input));
    }
  } catch (Exception e) {
    logger.error(CommonUtils.getExceptionTrace(e));
  }
  return null;
}

public static void main(String[] args) throws Exception {
  Integer foo = getProperty("123", Integer.class);
  System.out.println(foo);
}

Prints: 123.

Sign up to request clarification or add additional context in comments.

1 Comment

i specifically used class with packages so that they will not confilict with any other class with same name if anyone create just a hypothesis

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.