Generics simply aren't type-safe?

From http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf page 15:
In particular, the language is designed to guarantee that if your entire application has been compiled without unchecked warnings using javac -source 1.5, it is type safe.
However, I can create this:
import java.util.*;
public class TypeUnsafe
     static public <T extends Collection> void workaround(T a, T b)
          a.addAll(b);
     static public void main(String[] args)
          Collection<Integer> a = new ArrayList<Integer>();
          Collection<String> b = new ArrayList<String>();
          b.add("Bwahahaha");
          workaround(a, b);
          System.out.println(a.iterator().next().intValue()); // ClassCastException
}There are no casts or particular trickery involved, and this compiles without warnings using javac -source 1.5. Yet I just added a String to a Collection<Integer>. Despite T being defined as extending a raw type, the usual unchecked warning when calling a method with parameterised arguments on a raw type is not given.
On the positive side, it gives me a handy alternative to the NYI @SuppressWarnings :)
I've searched bug parade and the forums, but haven't come across this particular problem... I've only recently started playing with generics, so perhaps I'm missing some subtlety that explains why people aren't jumping up and down and screaming about this.
Sorry if this has been discussed before, and I'm not yet familiar enough with the terminology to have found it in my searches.

Few thoughts:
- The program kingguppy has presented is an example of program with false sense of security despite using generics - the generic program compiles even without a warning but in the end it throws ClassCastException. I hope that we won't find many generic programs with such characteric. I'd say that the program does not benefit of generics because there is no contract between container and containee as far as parameters of workaround() method are concerned. Actually, as Michael said, it uses raw type (Collection). If possible we should avoid using raw types in generic programs. By the way, do you know that raw types might be deprecated in the future?
- Micheal also sugested that in case when there is a conversion from parameterized type to raw type the compiler should emit a warning. I agree with him. I hope that kingguppy will file a bug report and let us know what "generic gurus" think about it. Funny, if the workaround() method were designed as
static public void notGenerifiedMethod(Collection a, Collection b) {
  a.addAll(b);
}the compiler would actually emit an unchecked warning. Perhaps, it's sometimes better not to use generified methods.
- The reason why I presented let's say a possible or different solution to the original problem is because in the end it matters only if we, developers, can produce a workable solution. The bosses don't like to hear that there are bugs... I hope you all know what I mean. Who knows, there might be a reader of this forum who will find it useful.
Your thoughts are welcomed.
Andrej

Similar Messages

  • I have type-safe generic array copying!

    Check this out. I get no warnings from this, and so far it seems to work fine, and it only takes twice the time of a normal array copy.
    All you have to do is pass in a dummy array of the same type as your inputArray, which under normal circumstances is very doable. The dummy array does not need to have the same dimension as the input array, which lets you use this as a static method in a utility class without feeling the burning need to make it throw an exception.
    It takes advantage of Collections' type-safe toArray() method.
         public static <T> T[] copyArray(T[] inputArray, T[] targetArray)
              return arrayToList(inputArray).toArray(targetArray);
         private static <T> ArrayList<T> arrayToList(T[] inputArray)
              ArrayList<T> returnValue = new ArrayList<T>();
              for(int i = 0; i < inputArray.length; i++)
                   returnValue.add(inputArray);
              return returnValue;

    And I like my tabs, thank you.Many people consider using tabs in code to be
    amatuerish. I can't say I disagree. Tabs are
    represented as different lengths depending on the
    editor. If you are using Eclipse, you can set it to
    insert a number of space when you hit tab instead of
    inserting tabs.I like tabs because they are an abstraction of indentation levels, something you don't get with spaces (unless you use one space per level), and therefore it makes more sense to me to use them. I use editors with good tab sizes that are also adjustable. Plus, I just like them better. So there.

  • Type Safe Collections

    Hello All,
    I want to have type safe collections. Today. when we do programming with collections it almost behaves like a scripting language with no data types. any thing which is an object goes in and comes out freely.
    what about having a Collection(vector, ArrayList) class which can contain objects of only one type.
    something like
    ArrayList<Integer> a = new ArrayList();
    regards,
    Abhishek.

    Here's my way of using generics in normal Java - not quite as good as a compile error - but it works, and gives you a runtime error on inserting an object of the wrong type.
    I did this when at Uni, hence all the funky comments (well, you can't expect the lecturers to actually read the code, can you?).
    Just something you may find useful:
    import java.util.*;
    ���An implementation of the Proxy pattern, designed to wrap any list, and make it accept
    ���objects of the specified type (subclasses are allowed) only, hence allowing a user of
    ���this class to 'trust' the Proxy list.
    public class TypeSafeList extends AbstractList implements Serializable
    ���protected List source;
    ���protected Class acceptable;
    ���/**
    ������@param list the list to assign.
    ������@exception java.lang.IllegalArgumentException if the list contains elements of a
    ������different type to that specified
    ���*/
    ���public TypeSafeList(List list,Class acceptable)
    ���{
    ������Iterator iterator = list.iterator();
    ������while( iterator.hasNext() )
    ���������if( !acceptable.isInstance( iterator.next() ) )
    ������������throw new IllegalArgumentException( list+" contains elements not of type "+acceptable);
    ������this.source=list;
    ������this.acceptable=acceptable;
    ���}
    ���/**
    ������Passes on the request to the underlying list. See java.util.List.
    ���*/
    ���public Object get(int index)
    ���{
    ������return source.get(index);
    ���}
    ���/**
    ������Passes on the request to the underlying list. See java.util.List.
    ���*/
    ���public int size()
    ���{
    ������return source.size();
    ���}
    ���/**
    ������Checks that the type of the parameter is valid, and then passes on the
    ������request to the underlying list. See java.util.List.
    ������
    ������@exception java.lang.IllegalArgumentException if the type of the parameter is
    ������invalid.
    ���*/
    ���public Object set(int index,Object element)
    ���{
    ������return source.set(index,checkType(element));
    ���}
    ���/**
    ������Passes on the request to the underlying list. See java.util.List.
    ���*/
    ���public Object remove(int index)
    ���{
    ������return source.remove(index);
    ���}
    ���/**
    ������Checks that the type of the parameter is valid, and then passes on the
    ������request to the underlying list. See java.util.List.
    ���*/���
    ���public void add(int index,Object object)
    ���{
    ������source.add(index,checkType(object));
    ���}
    ���/**
    ������Return the Class object this List is configured to accept.
    ���*/
    ���public Class getAcceptable()
    ���{
    ������return acceptable;
    ���}
    ���
    ���/**���
    ������Checks the validity of the parameter against the protected field 'acceptable'.
    ������@return object if object is valid.
    ������@exception java.lang.IllegalArgumentException if the argument is invalid.
    ���*/
    ���protected Object checkType(Object object) throws IllegalArgumentException
    ���{
    ������if (acceptable.isInstance(object))
    ���������return object;
    ������throw new IllegalArgumentException(object+" needs to be of type "+acceptable.getName());
    ���}
    }

  • Type safe bean interfaces (Java 5) and JBoss IDE

    I've posted this help request already in the appropriate JBoss forum.
    But unfortunately still without any response.
    Latest JBoss IDE versions support type safe business methods e.g. like
         * only for testing
         * @ejb.interface-method view-type = "both"
         * @ejb.permission role-name = "Default"
        public ArrayList<String> getSomeStrings()
        }But the interface methods will be always generated unsafe like
        * only for testing
       public java.util.ArrayList getSomeStrings(  )
          throws java.rmi.RemoteException;Is this a known problem or is something wrong with my xdoclet configuration?
    Thanks in advance
    Torsten

    Yep... I think that's what I found. By using public methods in my enum class to map it's string member to the EJB field I was able to effectively use my enum in the EJB. The container does it work with a String but the EJB's clients only deal with a enum field. That's what I originally intended so, thanks for your response.

  • What does it mean by "Deprecation of MBeanHome and Type-Safe Interfaces" ?

    The "Javadoc" for the type safe WebLogic MBean interfaces have this disclaimer;
    Deprecation of MBeanHome and Type-Safe Interfaces... This is a type-safe interface for a WebLogic Server MBean, which you can import into your client classes and access through weblogic.management.MBeanHome. As of 9.0, the MBeanHome interface and all type-safe interfaces for WebLogic Server MBeans are deprecated. Instead, client classes that interact with WebLogic Server MBeans should use standard JMX design patterns in which clients use the javax.management.MBeanServerConnection interface to discover MBeans, attributes, and attribute types at runtime.
    Link: http://otndnld.oracle.co.jp/document/products/wls/docs100/javadocs_mhome/weblogic/management/configuration/DomainMBean.html
    I don't understand what this means;
    1) Is all the WebLogic MBean interfaces in the "weblogic.management.configuration.*" deprecated?
    2) Is the usage of MBeanTypeService also deprecated. since it requires the an WebLogic MBean interface as input for it's getMBeanInfo method?
    3) If the WebLogic MBean interfaces will dispear, wil there be any reliable source for type information about WebLogic MBean since the information returned by MBeanTypeService.getMbeanInfo(), MBeanserver.getMbeanInfo() or WebLogicObjectName.getMbeanInfo() isn't consist in its naming schemes (tries to but..)?

    Hi,
    While scheduling background job, you can trigger the job based on existing job status as dependency or schedule the job based on the SAP Event.
    Dependency Job like first background job completes successfully then second followup job will executed other job will not triggered.
    Event Jobs: While importing data through transportation, some RDD* jobs automatically triggers. These are event based jobs.
    Regards,
    Ganesh
    ****Reward points if Helpful*****

  • Generic Method, How parameter type is determined

    For method
    <T> void fromArrayToCollection(T[] a, Collection<T> c) { ... } Why does
    fromArrayToCollection(sa, co);passes and
    fromArrayToCollection(oa, cs); fails.
    oa - Object Array, Object[]
    cs - Collection of String, Collection<String>
    sa - String Array, String[]
    co - Collection of Object, Collection<Object>
    What are the rules governing the type of T inferred by compiler?

    epiphanetic wrote:
    I think you still haven't fully understood the issue.
    I suggest, you also read the same generics tutorial by Gilad Bracha, section 6 from where I found this issue :). Ha! But I think it's misleading that that section uses arrays.
    In his words "It will generally infer the most specific type argument that will make the call type-correct." Its also mentioned that collection parameter type has to be supertype of Array parameter type but no reason is given. I wonder why it fails to infer correct type in second case.Assume you passed in an array of Objects, and a Collection of Strings, and it was possible that T would then be Object. Using Bracha's example implementation:
    static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
       for (T o : a) {
          c.add(o); // correct
    }Now imagine you had this code making use of it:
    Object[] objects = {Integer.valueOf(1), "hi", new Object()};
    Collection<String> strings = new LinkedList<String>();
    fromArrayToCollection(objects, strings);
    String string = strings.iterator().next(); //get first String, which is actually an IntegerTrying to get the first String would give a ClassCastException. So clearly that method cannot not be safely invoked.
    The reason I think he's confusing things by using the array is because you might get it in your head that this would be OK:
    static <T> void fromCollectionToCollection(Collection<T> one, Collection<T> two) {
       for ( T t : one ) {
          two.add(t);
    Collection<Object> col1; Collection<String> col2;
    doSomething(col1, col2);When clearly it's unsafe, as now your Collection of Strings might have a non-String in it! That's why I said this is more a nuance of generic arrays than of type inference proper.

  • Adobe Premier Elements 8 - Generic failure.  This type of file is not...

    Hi all,
    So the problem is this. When trying to add media to a project (two .avi files from a dv camera). When pushing add media, then it asks where is the file.
    When you search for the file(s) then it says "Generic failure. This type of file is not supported or the codec required is not installed."
    This just appeared, yeasterday everything was fine. I tryied to download codec packs etc and tryied to convert the files to .wmv .mov and so on but nothing helped.
    Help needed please.

    Hi,
    Camcorder type I dont know yet, because its not my computer or camera. Working on it to find out.
    But that I know that the video was transferred using 1394 port.
    Computer has the latest version of Quicktime. OS is Windows XP SP3. i7 processor (the computer is Dell E6410).
    And space it has enough

  • Help inheriting multiple generic interfaces of same type

    Hi-
    I am trying to re-factor some current code bloat.
    Here is the solution I want
    I want to define one generic subscriber interface, e.g.
    public interface Subscriber <TYPE> {
    public void valueChanges (TYPE T) ;
    And then I would like to (in theory) implements a class like this
    public class MyClass extends foo implements Subscriber<String> ,
    Subscriber <Integer> , Subscriber <Double> {
    public void valueChanged (String s) {
    public void valueChanged (Integer s) {
    public void valueChanged (Double s) {
    But this does not seem to be allowed becuase it says you can not inherit the
    same interface multiple times. I even tried something like this
    public interface Stringsubscriber implements Subscriber <String> for all the
    interfaces to specialize. That does not work.
    Can this be done (via some mechanism) in java or is this not possible.
    I am just learning the way generics work (I come from c++ world were templates
    are a bit more flexible and work a bit differently so its trying).
    Any hlep would be great.
    thanks in advance
    matt

    OK, Bruce, I'll bite: how do you attach
    parameterized types as annotation member values?
    There's no ".class" for them. It must be textual,
    , right? No.
    Actually I don't attach them as such, I put them somewhere else where I can find them by association.
    And you parse these stringual declarations
    later?The mirror API does not have an equivalent method to com.sun..javadoc.ClassDoc.findClass(String name), so you can't do it textually unless you require every type to be fully qualified. Thats too ugly for me.
    I tried writing a recursive annotation like this@interface Type {
        Class<?> value();
        Type[] args() default {};
    }but you can't write cyclic annotations (whose members are of its own type, directly or indirectly).
    So I thought that since I was annotating a class, I would just create some placeholder interfacesinterface S2WFGC1<T1> {}
    interface S2WFGC2<T1,T2> {}
    thru
    interface S2WFGC15<T1,T2,... T15> {}and do this
        @MyAnnotation(base=Map.class, add=@Flavor(EventDispatcher.class))
    class MyClass implements S2WFGC2<
                    Map<String,Integer>,
                    EventDispatcher<FooListener,FooEvent>
                > {
    }which gets interpreted as
        @MyAnnotation(
            base=Map<String,Integer>,
            add=@Flavor(EventDispatcher<FooListener,FooEvent>)
    class MyClass {}So I just put the raw type in the annotation, and for each of those (because the annotation is more complex than above), I get the type parameters from the S2WFGCn interface. I just use whichever S2WFGCn interface has the right number of type parameters.
    For each type in the annotation, if it is generic, I just read the next type argument from the S2WFGCn superinterface and use that instead (but error if its raw type is not the same as the annotation value). Each S2WFGCn actually extends S2WFGC, which makes it easy to find the S2WFGCn amongst (possibly other) superinterfaces.
    The S2WFGCn interfaces are sort of marker interfaces, but as well as having no methods, they also have no meaning. They are more like a variable for holding an array of types at the meta level.
    Sorry, but thats the best I can come up with. Its not pretty for sure, and I'd rather have a nicer mechanism, but for this application at least, the benefits are still positive, since in most cases there are no generic classes, so all the trickery disappears, and when there are generics, the ends justify the means.
    If only the JSR-175 EG had realised that generics was a meta type of the language...
    This was their biggest failure by a country mile.

  • Axis - Using type safe enumerations as parameters.

    I defined the following:
    interface A {
    foo(E x);
    where class E is a type safe enumeration (NOT a Java1.5 enum).
    When using java2wsdl | wsdl2java i get:
    interface A' {
    foo(String x);
    And then all the stubs and skeletons are implementing A' so I can't use my A. How can I stop axis from doing this?

    Hi,
    AFAIK, you can't. I'm not an expert though, so everything below may not be the best solution.
    The best way I have found for dealing with enums is to declare them as such in your schema, viz:
          <simpleType name="HoldStatus">
            <annotation>
              <documentation>The status of a hold.</documentation>
            </annotation>
            <restriction base="string">
              <enumeration value="INACTIVE"/>
              <enumeration value="ACTIVE"/>
            </restriction>
          </simpleType>Then, most WSDL->Java tools will do something sensible with this, making their own form of enum. I don't know about Axis, but Weblogic's wsdl2service does this.
    Then you still have to map between the generated enum and your one. This is the best solution I'm aware of, though.
    As far as running java2wsdl then wsdl2java - I'm not aware of any tools that will do 'round tripping' like this successfully. I'd be keen to hear of some if there are any though :-D
    -Tim

  • Type-safe enum in CMP EJB field...

    Is it possible to use a type-safe enum like this in an EJB CMP field?
    I have tried to do that but although the code compiles I get errors.
    package dataBeansPkg;
    import java.io.Serializable;
    import java.io.ObjectStreamException;
    import java.util.HashMap;
    public final class Estado implements Serializable
    private static final String ACTIVODESC = "Activo";
    private static final String INACTIVODESC = "Inactivo";
    private static final String ELIMINADODESC = "Eliminado";
    private static final String BLOQUEADODESC = "Bloqueado";
    private static HashMap VALUES = new HashMap();
    private final String status;
    private final String descripcion;
    public static final Estado ACTIVO = new Estado("A", ACTIVODESC);
    public static final Estado INACTIVO = new Estado("I", INACTIVODESC);
    public static final Estado ELIMINADO = new Estado("E", ELIMINADODESC);
    public static final Estado BLOQUEADO = new Estado("B", BLOQUEADODESC);
    protected Estado()
    this.status = null;
    this.descripcion = null;
    protected Estado(String estado, String descripcion)
    this.status = estado;
    this.descripcion = descripcion;
    VALUES.put(estado, this);
    public String getValor() { return status; }
    public String getEstado() { return status; }
    public String getDescripcion() { return descripcion; }
    public String toString() { return getValor(); }
    public final boolean equals(Object o) { return super.equals(o); }
    public final int hashCode() { return super.hashCode(); }
    public static Estado find(String estado)
    if(VALUES.containsKey(estado)) {
    return (Estado)VALUES.get(estado);
    return null;
    public Object readResolve()
    Object result = find(status);
    if(result != null)
    return result;
    else
    return INACTIVO; // valor por omision
    Whenever I run a client using the bean with a field associated to this enum, I get...
    java.io.StreamCorruptedException: Caught EOFException while reading the stream header
    and
    Error loading state: java.io.StreamCorruptedException: Caught EOFException while reading the stream header
    Is it possible to use a type-safe enum as a field in an CMP bean?

    Yep... I think that's what I found. By using public methods in my enum class to map it's string member to the EJB field I was able to effectively use my enum in the EJB. The container does it work with a String but the EJB's clients only deal with a enum field. That's what I originally intended so, thanks for your response.

  • What's "type-safe" ?

    when something is type-safe, what does that mean?

    http://en.wikipedia.org/wiki/Type_safe
    It's amazing what the wide world of web contains.

  • Need help with generic class with comparable type

    Hi. I'm at University, and I have some coursework to do on writing a generic class which offers ordered binary trees of items which implement the comparable interface.
    I cant get the code to compile which I have written.
    I get the error: OBTComparable.java uses unchecked or unsafe operations
    this is the more detailed information of the error when I compile with -Xlint:unchecked
    OBTComparable.java:62: warning: [unchecked] unchecked call to insert(OBTType) as
    a member of the raw type OBTComparable
    left.insert(insertValue);
    ^
    OBTComparable.java:64: warning: [unchecked] unchecked call to insert(OBTType) as
    a member of the raw type OBTComparable
    right.insert(insertValue);
    ^
    OBTComparable.java:75: warning: [unchecked] unchecked call to find(OBTType) as a
    member of the raw type OBTComparable
    return left.find(findValue);
    ^
    OBTComparable.java:77: warning: [unchecked] unchecked call to find(OBTType) as a
    member of the raw type OBTComparable
    return right.find(findValue);
    ^
    and here is my code for the class
    public class OBTComparable<OBTType extends Comparable<OBTType>>
      // A tree is either empty or not
      private boolean empty;
      // If the tree is not empty then it has
      // a value, a left and a right.
      // These are not used it empty == true
      private OBTType value;
      private OBTComparable left;
      private OBTComparable right;
      // Create an empty tree.
      public OBTComparable()
        setEmpty();
      } // OBTComparable
      // Make this tree into an empty tree.
      private void setEmpty()
        empty = true;
        value = null; // arbitrary
        left = null;
        right = null;
      } // setEmpty
      // See if this is an empty (Sub)tree.
      public boolean isEmpty()
      { return empty; }
      // Get the value which is here.
      public OBTType getValue()
      { return value; }
      // Get the left sub-tree.
      public OBTComparable getLeft()
      { return left; }
      // Get the right sub-tree.
      public OBTComparable getRight()
      { return right; }
      // Store a value at this position in the tree.
      private void setValue(OBTType requiredValue)
        if (empty)
          empty = false;
          left = new OBTComparable<OBTType>(); // Makes a new empty tree.
          right = new OBTComparable<OBTType>(); // Makes a new empty tree.
        } // if
        value = requiredValue;
      } // setValue
      // Insert a value, allowing multiple instances.
      public void insert(OBTType insertValue)
        if (empty)
          setValue(insertValue);
        else if (insertValue.compareTo(value) < 0)
          left.insert(insertValue);
        else
          right.insert(insertValue);
      } // insert
      // Find a value
      public boolean find(OBTType findValue)
        if (empty)
          return false;
        else if (findValue.equals(value))
          return true;
        else if (findValue.compareTo(value) < 0)
          return left.find(findValue);
        else
          return right.find(findValue);
      } // find
    } // OBTComparableI am unsure how to check the types of OBTType I am comparing, I know this is the error. It is the insert method and the find method that are causing it not to compile, as they require comparing one value to another. How to I put the check in the program to see if these two are of the same type so they can be compared?
    If anyone can help me with my problem that would be great!
    Sorry for the long post, I just wanted to put in all the information I know to make it easier for people to answer.
    Thanks in advance
    David

    I have good news and undecided news.
    First the good news. Your code has compiled. Those are warnings not errors. A warning is the compiler's way of saying "I understand what you are asking but maybe you didn't fully think through the consequences and I just thought I would let you know that...[something] "
    In this case it's warning you that you aren't using generics. But like I said this isn't stopping it from compiling.
    The undecided news is the complier is warning you about not using generics. Are you supposed to use generics for this assignment. My gut says no and if that's true then you have no problem. If you are supposed to use generics well then you have some more work.

  • Oracle plugin install breaks "Generic JDBC_1.x server type"

    Using Eclipse Europa w/Oracle plugin 1.0.0.464. After installing the Oracle plugin, my Generic JDBC 1.x connection profiles are now erroneously associated with server type "Oracle_10.x" instead of "Generic JDBC_1.x".
    Let me know if you need add'l details.
    - Ron

    But no, we need to update your info, a version of oracle for mac intel exists,
    on my macbook I have oracle 10gR2 installed, it works well,
    the error I got when I tried to install oracle on MacOsX 10.5.7 Server
    look here
    http://www.oracle.com/technology/software/products/database/oracle10g/htdocs/10204macsoft_x86-64.html
    http://blog.rayapps.com/2009/04/12/how-to-install-oracle-database-10g-on-mac-os-x-intel/

  • Are the generic batteries sold on eBay safe?

    My battery isn't dead, but the battery icon says "Replace Soon" on it, and my battery has bloated a little(I understand this to be normal of macbook batteries that are dying, is that correct?). Apple brand batteries cost around $100, but on eBay, you can find all kinds of generic macbook batteries sold by third-party companies like Poker Bridge, Zhaoyu, Cnbatteries, Electriczone, emmasilmon, AdapterMonster, Hootoodeals, notebookcompany, etc, for $33-34. I just want to know if these batteries are safe, will hold a charge for a decent period of time, will last, etc, or if they are so much cheaper for a reason. Is it ok to go with one of them or am I better off shelling out the cash for the Apple battery?

    Jon R wrote:
    my battery has bloated a little(I understand this to be normal of macbook batteries that are dying, is that correct?).
    I've burned through a number of them and have never seen one bloated.
    I just want to know if these batteries are safe, will hold a charge for a decent period of time, will last, etc, or if they are so much cheaper for a reason.
    Why don't you just buy one of these batteries from a local store like Target, Best Buy, Micro Center, etc. It's OK. I'll wait....
    Is it ok to go with one of them or am I better off shelling out the cash for the Apple battery?
    I don't like to take chances with anything involving power. I would also never buy anything that was only available on eBay.

  • Iterating through a generic list of unknown type

    Hi,
    I am in the process of creating pdf reports for my project.I have to deal with a persistence api to get the data for the report.The data will be in the form of a list,like List<SomeObject>,all these lists returned by the persistence framework contains object of some type which implements a common interface.But through that interface I wont be able to get all the data for my reports.So I am looking for a generic way for iterating through the list,by providing some metadata for the data within the list. I am planning to use reflection to query through the list.Is there any feature of generic,through which I can easily iterate through this unknown type,preferrably a combination of reflection and generics,I want to reduce the LOC.Any suggestions??

    If the List returned by the framework isn't parameterized, Like
    public List<K> getList(Class<K> classType);
    then you have to cast it to the appropriate type. If you are not sure about the type of the Objects in the list, and you have a bunch of class types you could expect from the list, then you could use instanceof operator.
    If it could be Class A or B, then
    if (obj instanceof A){
    A castObject = (A) obj;
    else if(obj instanceof B){
    B castObject = (B)obj;
    }Even to do reflection to invoke methods, you need to know the method Names. Which tells me you have the knowledge of what could come out of the list. So cast them. Invoking methods using reflection is really slow.

Maybe you are looking for

  • Yoga 2 pro: will a mouse work with the machine in tablet mode?

    just curious, a pre purchase question...will the yoga 2 work with a mouse when flipped open and in "tablet' mode? thanks. Solved! Go to Solution.

  • Script - Changing Submission Format

    All I need a line of Javascript of FormCalc code that changes the form's submission type from XDP to PDF. I have arrived at the following but am unsure if it is correct: $.#event.#submit.format = "PDF"; Any ideas?

  • Can lens correction be applied to Photoshop Elements 12

    I have recently decided to get into Drone Photography.  I have a DJI Phantom 2 Plus video and have recently purchased Photoshop Elements 12; there is "fish eyeing" that I would like to be able to correct.  Is there a way to upgrade my current version

  • Size in InputField size in FileUpload

    Does anybody know why a htmlb:InputField with size="20" is much smaller that a htmlb:fileupload with size="20"? <htmlb:inputField id = "att" size = "20"/>     <htmlb:fileUpload id = "upl" size = "20" onUpload = "HdlUp"/>

  • In what table is the Quality Notification have the Delete Flag?

    I have a report that list all open tasks for a Quality Notification.  There are notifictions that I went into QM02 and deleted the notification.  I do not want these to show up on the report.  Where would I find the "delete" flag?  Thanks