简体   繁体   中英

java generics: runtime type-checking to determine a strategy

how may I select a different method based upon a Generic type?

Simply I have a class parametrized with a generic type and I have to select the correct PreparedStatement setter according to the T type:

Class CustomFieldsTypeManager<T> {
   ArrayList<T> data;

   public void setUpStatement(PreparedStatement st){
      ...
      if ( **T==String** ){
         st.setString(index, (String) data<T>.get(dt_index);
      } else if ( **T==Integer** ){
         st.setInt(index, (String) data<T>.get(dt_index);
      }
      ...
   }
}

Because of type erasure that information on generics is lost at runtime. You should try to exploit parametric polymorphism in a different way, by providing specialization of the classes:

class CustomFieldsTypeManager<T> {
   ArrayList<T> data;

   abstract void setUpStatement(PreparedStatement st);
}

class StringCustomFieldsTypeManager extends CustomFieldsTypeManager<String> {
   void setUpStatement(PreparedStatement st) {
     st.setString(index, data.get(dt_index)); // data it's already an ArrayList<String>
   }
}

There are also ways to check it at runtime but this kinda defeats the good points of generics an inheritance even if they're as safe as this solution (must they must be correctly written).

You're looking for instanceof :

if ( data.get(dt_index) instanceof String ) {
    //...
}

You can't. But what you could do, is:

class CustomFieldsTypeManager<T> {
    private Class<T> type;
    public CustomFieldsTypeManager(Class<T> type) {
        this.type = type;
    }
}

Then:

CustomFieldsTypeManager<String> m = new CustomFieldsTypeManager<String>(String.class);

And finally:

public void setUpStatement(PreparedStatement st) {
    if (type.equals(String.class)){
        st.setString(index, (String) data<T>.get(dt_index);
    } else if (type.equals(Integer.class)){
        st.setInt(index, (String) data<T>.get(dt_index);
    }
}

Or, simply use the PreparedStatement#setObject method instead of the ones you're using.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM