How to return a list of generic type

I can create a method that takes a Class as parameter and return the same type:
public <T> T getSomthing(Class<T> c) throws Exception {
        return c.newInstance();
}My question is, can I modify this method to return a List of the same type as input class c? If so, how?

Hi,
import java.util.ArrayList;
import java.util.List;
public class ReturnList {
    @SuppressWarnings("unchecked")
    public <T> List<T> getList() {
     return new ArrayList();
}Piet

Similar Messages

  • How to create an array with Generic type?

    Hi,
    I need to create a typed array T[] from an object array Object[]. This is due to legacy code integration with older collections.
    The method signature is simple:public static <T> T[] toTypedArray(Object[] objects)I tried using multiple implementations and go over them in the debugger. None of them create a typed collection as far as I can tell. The type is always Object[].
    A simple implementation is just to cast the array and return, however this is not so safe.
    What is interesting is that if I create ArrayList<String>, the debugger shows the type of the array in the list as String[].
    If I create ArrayList<T>, the class contains Object[] and not T[].
    I also triedT[] array = (T[]) Array.newInstance(T[].class.getComponentType(), objects.length);And a few other combinations. All work at runtime, create multiple compilation warnings, and none actually creates T[] array at runtime.
    Maybe I am missing something, but Array.newInstace(...) is supposed to create a typed array, and I cannot see any clean way to pass Class<T> into it.T[].class.getComponentType()Returns something based on object and not on T, and T.class is not possible.
    So is there anything really wrong here, or should I simply cast the array and live with the warnings?
    Any help appreciated!

    Ok. May be you could keep information about generic type in the your class:
    public class Util {
        public static <T> T[] toTypedArray(Class<T> cls, Object[] objects){
            int size = objects.length;
            T[] t = (T[]) java.lang.reflect.Array.newInstance(cls, size);
            System.arraycopy(objects, 0, t, 0, size);
            return t;
    public class Sample<T> {
        Class<T> cls;
        T[] array;
        public Sample(Class<T> cls) {
            this.cls = cls;
        public void setArray(Object[] objects){
            array = Util.toTypedArray(cls, objects);
        public T[] getArray(){
            return array;
        public static void main(String[] args) {
            Object[] objects = new Object[] { new LinkedList(), new ArrayList()};
            Sample<List> myClass = new  Sample<List>(List.class);
            myClass.setArray(objects);
            for(List elem: myClass.getArray()){
                System.out.println(elem.getClass().getName());
    }

  • How to return a list of class from a package

    Hi,
    I'm trying to create a RPG game with 50 characters. There will be a superclass, and each character is a subclass that extends from the superclass. Each will have unique abilities that will be functions. These classes will be thrown into a package.
    I would like to know the code for returning the list of classes in that package. That way, I can present them as a list for the player to choose just a handful of characters to start out with.
    Thanks in advance         

    Hi u can use the this class
    flash.utils.describeType;
    Regards
    Sumit Agrawal

  • How to return Values from Oracle Object Type to Java Class Object

    Hello,
    i have created an Oracle Object Types in the Database. Then i created Java classes with "jpub" of these types. Here is an example of the type.
    CREATE OR REPLACE TYPE person_type AS OBJECT
    ID NUMBER,
    vorname VARCHAR2(30),
    nachname VARCHAR2(30),
    geburtstag DATE,
    CONSTRUCTOR FUNCTION person_type RETURN SELF AS RESULT,
    CONSTRUCTOR FUNCTION person_type(p_id NUMBER) RETURN SELF AS RESULT,
    CONSTRUCTOR FUNCTION person_type(p_vorname VARCHAR2,
    p_nachname VARCHAR2,
    p_geburtstag DATE) RETURN SELF AS RESULT,
    MEMBER FUNCTION object_exists(p_id NUMBER) RETURN BOOLEAN,
    MEMBER PROCEDURE load_object(p_id NUMBER),
    MEMBER PROCEDURE save_object,
    MEMBER PROCEDURE insert_object,
    MEMBER PROCEDURE update_object,
    MEMBER PROCEDURE delete_object
    MEMBER PROCEDURE load_object(p_id NUMBER) IS
    BEGIN
    SELECT p.id, p.vorname, p.nachname, p.geburtstag
    INTO SELF.ID, SELF.vorname, self.nachname, SELF.geburtstag
    FROM person p
    WHERE p.id = p_id;
    END;
    My problem is, that if i use the member function "load_object" from my java app it doesnt return the selected values to the java class and i dont know why. I use the java class like this:
    PersonObjectType p = new PersonObjectType();
    p.load_object(4);
    There is a reocrd in the database with id = 4 and the function will execute successful. But if i try to use "p.getVorname()" i always get "NULL". Can someone tell me how to do that?
    Thanks a lot.
    Edited by: NTbc on 13.07.2010 15:36
    Edited by: NTbc on 13.07.2010 15:36

    CallableStatement =
    "DECLARE
    a person_type;
    BEGIN
    a.load_object(4);
    ? := a;
    END;"
    And register as an out parameter.
    Edited by: michael76 on 14.07.2010 05:01

  • How to return a list?

    Hi m assignment is to create a linked list implementation..
    so far i have this..
    public class Set<Value> {
    Value Element;
    Set<Value> next;
    Set(Value data)
                Element=data;
                next=null;
            Set(Value data, Set n)
                Element = data;
                next    = n;
    public interface MySet<Value> {
    boolean isIn(Value v);
    void add(Value v);
    void remove(Value v);
    MySet union(MySet s);
    MySet intersect(MySet s);
    MySet difference(MySet s);
    int size();
    void printSet();
    public class MyLLSet<Value> implements MySet<Value>{
        private Set<Value> head;
    public MyLLSet(){
        head=new Set(null);  
    public boolean isIn(Value v){
        Set<Value> p;
        p=head;
        boolean flag=false;
         while(p.next!=null){
            p=p.next;
            if(p.Element==v){
                flag=true;
    return flag;
    public void add(Value v){
        Set<Value> p;
        Set<Value> q;
        p=head;
        q=head.next;
        while(p.next!=null){
            p=p.next;
            q=q.next;
        p.next=new Set(v,q);
    public void remove(Value v){
    Set<Value> p;
    Set<Value> q;
    p=head;
    q=head.next;
    while(p.next!=null){
         p=p.next;
         q=q.next;
         if(p.Element==v){
             p.next=p.next.next;
             q.next=null;
             break;
    public MySet union(MyLLSet s){
        Set<Value> p;
        Set<Value> q;
        p=s.head;
        q=this.head;
        while(p.next!=null){
            p=p.next;
        p=q.next;
        s.head.next=null;
    RETURN ???
    }However in my union method i cant figure out what to return.. i am sure that the method creates a union of two lists.. but how do i return the final unionized list.... ( i am new to programming so sorry if i dont make sense)
    Edited by: haramino1 on Mar 22, 2009 1:31 PM

    Have some patience! You can't expect an answer in 10 minutes.
    Your original post looked like you wanted to make an implementation of a linked list, using a set as the underlying code (which doesn't make a lot of sense). However, your real assignment, as you stated later, is to make an implementation of a set, with a linked list as the underlying code.
    In your original post, your Set<Value> doesn't make sense to be your Set class. It does make sense to have that code as your linked list's "node" class. So, rename it from Set<Value> to Node<Value>. Everywhere in that class that says "Set" should say "Node". It will only confuse you more if you call it "Set" when it is not a "Set" (it surely confused me!). Also, "Element" should be lowercase "element" (to follow standard naming conventions).
    You want to make a linked list class that implements everything in the MySet<Value> interface. So, your MyLLSet<Value> should have all of those methods. Your MyLLSet should have one variable (which you have, but you call it Set<Value>, it should be Node<Value>).
    private Node<Value> head;Your MyLLSet constructor probably shouldn't set head to a new Node with a null value (otherwise, your Set will always include a null member). The MyLLSet constructor probably doesn't need to do anything, so you can just remove that whole constructor and let the compiler generate its standard no-argument constructor.
    When comparing values for equality in isIn, you probably want to use .equals, not ==:
    if (p.element == v) // WRONGshould be:
    if (p.element.equals(v)) // CORRECTOtherwise, you are only comparing reference values, not the data they point to. So, for instance, if Value was a String, you wouldn't be able to write code that asked the user for a String value to test if the String was in the Set--I don't think you'd ever be able to get "true" for the answer.
    In isIn, your test should not be p.next != null --it should be "p != null". Otherwise, if p is null, you will get a NullPointerException trying to get "next". You want:
    while (p != null) {
       // Test p.element for equality to v.
       //        If equal, you can break out of the 'for' loop.
       // Set p to p.next.
    }Similarly in other methods, you need to check p != null . Your 'add' method is wrong--you didn't check duplicates, for one thing. Your loop isn't right, either.

  • How to return a httpservletresponse for generic servlets II

    I have a servlet that do a call service to another machine( the service
              can be so different), and I would like to know if there is possible to
              return the "servletresult" in the "httpservletresult" or somethiing
              similar,because
              I don´t know which are the parameters to return , and i would like to
              manipule these parameters in the client. So, i want don´t use
              "getParameterValues" of "servletresult".
              I would like to return a object java. It is like to say that the result of
              the service call ("servletresult") is passed directly to the
              "httpservletresponse" and not pass every parameter (read by name ) between
              "servletresult" and "httpservletresponse".
              Thanks
              

    I am not sure if I am answering your question fully but here goes:
              I have a pack of utilities that I use for handling servlet requests.
              One of them helps to transform an HTTPRequest object into a HashMap.
              The objective was to make the processing as web-independent as
              possible. So what you get is a generic java object which has all the
              data of the HTTP Request. You can use it any way you want. I am
              attaching the code below. It does the basic job but pls remember that
              it was designed for a slightly different purpose:
              * Converts an HTTPServletRequest object to an equivalent HashMap
              public boolean mapRequest(HttpServletRequest req, Map input)
              try
              Enumeration reqEnum = req.getParameterNames();
              String keystr;
              String valstr;
              while(reqEnum.hasMoreElements())
              keystr = (String)reqEnum.nextElement();
              valstr = req.getParameter(keystr);
              input.put(keystr, valstr);
              return true;
              catch(Exception e)
              return false;
              oscar alarcon wrote:
              >
              > I have a servlet that do a call service to another machine( the service
              > can be so different), and I would like to know if there is possible to
              > return the "servletresult" in the "httpservletresult" or somethiing
              > similar,because
              > I don´t know which are the parameters to return , and i would like to
              > manipule these parameters in the client. So, i want don´t use
              > "getParameterValues" of "servletresult".
              > I would like to return a object java. It is like to say that the result of
              > the service call ("servletresult") is passed directly to the
              > "httpservletresponse" and not pass every parameter (read by name ) between
              > "servletresult" and "httpservletresponse".
              >
              > Thanks
              

  • How to return a list of customer  datatype in jax-ws 2.0?

    @WebService()
    public class TestWS{
         @WebMethod
         public List<CustomType> doWS(Integer userId)
            Business biz = new Business();
            return biz.doWS();
    }Thx!

    This should work, what problem you are facing?

  • How to return a list of Application Systems which share another one?

    Hi,
    In Designer 6 I have an application system which is shared by lots of other application systems. Is there an easy way to query the Designer metamodel to return such a list - I can't see which table(s) might hold this info.
    Trawling through the RON will take way too long and I might miss one.
    Thanks,
    Antony

    Roel,
    Thanks - of course, it's an object in the application system that is shared... but you knew what I meant!
    When I try to check this as per your post, I get the following error.
    "CDI-20902: No broadcast notification targets found in the registry." Designer help gives the following:
    Cause: Matrix diagrammer cannot find any diagrammer notification targets in the registry.
    Action: Reinstall product set or install entries into the registry from the install process.
    What does this mean - reinstalling Designer to get this to work?
    Thanks,
    Antony

  • How to return a "HttpServletResponse" for generic servlets (please Help me)

    I have a servlet that do a call service to another machine( the service
              can be so different), and I would like to know if there is possible to
              return to the client the "servletresult" in the "httpservletresult" or
              something
              similar("servletresult" is a class of "bea.jolt". and I utilizes for
              conectivity with TUXEDO).
              I am doing the call to the servlet in an application java(via URL and
              parameteres), not in browser.
              I don´t know which are the parameters to return , and i would like to
              manipule these parameters in the client. So, i want don´t use
              "getParameterValues" of "servletresult".
              I would like to return a object java. It is like to say that the result of
              the service call ("servletresult") is passed directly to the
              "httpservletresponse" and not pass every parameter (read by name ) between
              "servletresult" and "httpservletresponse".
              Thanks
              

    I have a servlet that do a call service to another machine( the service
              can be so different), and I would like to know if there is possible to
              return to the client the "servletresult" in the "httpservletresult" or
              something
              similar("servletresult" is a class of "bea.jolt". and I utilizes for
              conectivity with TUXEDO).
              I am doing the call to the servlet in an application java(via URL and
              parameteres), not in browser.
              I don´t know which are the parameters to return , and i would like to
              manipule these parameters in the client. So, i want don´t use
              "getParameterValues" of "servletresult".
              I would like to return a object java. It is like to say that the result of
              the service call ("servletresult") is passed directly to the
              "httpservletresponse" and not pass every parameter (read by name ) between
              "servletresult" and "httpservletresponse".
              Thanks
              

  • How to return a list of opportunities for a given contact

    Do you know how to do this? I looked at the Contact.xml (ws 2.0) QueryPage method but there's no ListofOpportunities. Below is my code so far
    <soapenv:Body>
    <ns:ContactQueryPage_Input>
    <ListOfContact>
              <Contact>
                   <Id>='ADSA-8D59T5'</Id>
                   <ContactEmail/>
              </Contact>
    </ListOfContact>
    </ns:ContactQueryPage_Input>
    </soapenv:Body>

    I have to Querypage on the Opportunity object.

  • JFileChooser Listing Acceptable File Types

    How do you display to the user the acceptable file types in JFileChooser.

    The getDescription method of the FileFilter should return the list of file types that the filter accepts. If you create a filter that only takes jpg and bmp files, then the getDescription should return something like "*.jpg, *.bmp"When you add the filter to the filechooser, it's decription get's displayed when it's chosen.

  • Xsd:list using complex type ??

    Hello,
    I have modified world.xsd from (www.manojc.com... sample8)
    My customer wants to return a list of complex types. In this case list of Country (CountryList)
    Here is my schema and I run autotype target. produces errors
    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    xmlns:tns="http://tutorial/sample8/"
    targetNamespace="http://tutorial/sample8/">
    <xsd:complexType name="World">
    <xsd:sequence>
    <xsd:element type="xsd:string" name="name"
    minOccurs="1" nillable="true" maxOccurs="1" />
    <xsd:element type="tns:Country" name="country"
    minOccurs="1" maxOccurs="unbounded" />
    </xsd:sequence>
    <xsd:attribute name="population" type="xsd:long" />
    </xsd:complexType>
    <xsd:complexType name="Country">
    <xsd:sequence>
    <xsd:element type="xsd:string" name="name" minOccurs="1" />
    </xsd:sequence>
    <xsd:attribute name="population" type="xsd:long" />
    <xsd:attribute name="abbreviations">
    <xsd:simpleType>
    <xsd:list itemType="tns:TwoCharString" />
    </xsd:simpleType>
    </xsd:attribute>
    </xsd:complexType>
    <xsd:simpleType name="CountryList">
         <xsd:list itemType="tns:Country"/>
    </xsd:simpleType>
    <xsd:element name="countries" type="tns:CountryList"/>
    <xsd:complexType name="EUCountry">
    <xsd:complexContent>
    <xsd:extension base="tns:Country">
    <xsd:sequence>
    <xsd:element name="exchangeInfo" type="tns:ExchangeInformation" />
    </xsd:sequence>
    </xsd:extension>
    </xsd:complexContent>
    </xsd:complexType>
    <xsd:simpleType name="TwoCharString">
    <xsd:restriction base="xsd:NCName">
    <xsd:length value='2' />
    </xsd:restriction>
    </xsd:simpleType>
    <xsd:complexType name="ExchangeInformation">
    <xsd:simpleContent>
    <xsd:restriction base="xsd:float">
    <xsd:maxInclusive value="10000.0" />
    <xsd:attribute name="currency" type="tns:TwoCharString" />
    </xsd:restriction>
    </xsd:simpleContent>
    </xsd:complexType>
    </xsd:schema>

    What I have tryed is to do analyze the dbms_xml packages and I tried to do it the same way with the result:
    SQL> declare
    2 bar long raw;
    3
    4 FUNCTION foo RETURN raw IS
    5 EXTERNAL
    6 NAME "tidyCreate"
    7 LANGUAGE C
    8 LIBRARY TIDY_LIB
    9 PARAMETERS ( RETURN );
    10 begin
    11 bar := '1';
    12 bar := foo;
    13
    14 dbms_output.put_line(bar);
    15 end;
    16 /
    declare
    FEHLER in Zeile 1:
    ORA-06525: Lõngenfehlanpassung bei CHAR- oder RAW-Daten
    ORA-06512: in Zeile 4
    ORA-06512: in Zeile 12

  • Tutorial for make a non-generic type class from a generic type interface

    Hi there,
    How can I make a non-generic type class from a generic type interface?
    I appreciate if somebody let me know which site can help me.
    Regards
    Maurice

    I have a generic interface with this signature
    public interface IELO<K extends IMetadataKey>
    and I have implemented a class from it
    public class CmsELOImpl<K extends IMetadataKey> implements IELO<K>, Cloneable, Serializable
    then I have to pass class of an instance CmsELOImpl to AbstractJcrDAO class constructor whit below signature
    public abstract class AbstractJcrDAO<T> implements JcrDAO<T> {
    public AbstractJcrDAO( Class<T> entityClass, Session session, Jcrom jcrom ) {
              this(entityClass, session, jcrom, new String[0]);
    So I have made another class extended from AbstractJcrDAO. Below shows the code of this class and itd constructor
    public class ELODaoImpl extends AbstractJcrDAO<CmsELOImpl<IMetadataKey>> {
         public ELODaoImpl( Session session, Jcrom jcrom ) {
         super(CmsELOImpl.class , session , jcrom, MIXIN_TYPES);
    and as you see in its constructor I am calling the AbstractJcrDAO constructor by supper method
    then I got this error on the line of super method
    The constructor AbstractJcrDAO(class<CmsELOImpl>, session, Jcrom, String[]) is undefined.
    as I know java generics are implemented using type erasure. This generics are only
    in the java source file and not in the class files. The generics are only used by the compiler and
    they are erased from the class files. This is done to make generics compatible with (old) non generics java code.
    As a result the class object of AbstractJcrDAO<CmsELOImpl<IMetadataKey>>
    is AbstractJcrDAO.class. The <CmsELOImpl<IMetadataKey>> information is
    not available in the class file. As far as I understand it, I am looking a way
    to pass <CmsELOImpl<IMetadataKey>>, if it is possible at all.
    Maurice

  • How to return new blob object?

    Hi,
    I am trying to find documentation on how to return a custom abstract data type (ADT) using the CREATE TYPE... and BLOB interface.
    How can I return a new object type defined inside a blob. Can I return a blob (without initializing the lob locator first)?
    Please advise.

    Hi,
    Please check the below link.
    http://docs.oracle.com/cd/E24693_01/appdev.11203/e17126/create_type.htm
    Regards,
    Sailaja

  • How To: Use reflection to create instance of generic type?

    I would like to be able to use reflection to instantiate an instance of a generic type, but can't seem to avoid getting type safety warnings from the compiler. (I'm using Eclipse 3.1.1) Here is a trivial example: suppose I want to create an instance of a list of strings using reflection.
    My first guess was to write the following:
    Class cls = Class.forName("java.util.ArrayList<String>");
    List<String> myList = cls.newInstance();The call to Class.forName throws a ClassNotFoundException. OK, fine, so I tried this:
    Class cls = Class.forName("java.util.ArrayList");
    List<String> myList = cls.newInstance();Now the second line generates the warning "Type safety: The expression of type List needs unchecked conversion to conform to List<String>".
    If I change the second line to
    List<String> myList = (List<String>)cls.newInstance();then I get the compiler warning "Type safety: The cast from Object to List<String> is actually checking against the erased type List".
    This is a trivial example that illustrates my problem. What I am trying to do is to persist type-safe lists to an XML file, and then read them back in from XML into type-safe lists. When reading them back in, I don't know the type of the elements in the list until run time, so I need to use reflection to create an instance of a type-safe list.
    Is this erasure business prohibiting me from doing this? Or does the reflection API provide a way for me to specify at run time the type of the elements in the list? If so, I don't see it. Is my only recourse to simply ignore the type safety warnings?

    Harald,
    I appreciate all your help on this topic. I think we are close to putting this thing to rest, but I'd like to run one more thing by you.
    I tried something similar to your suggestion:public static <T> List<T> loadFromStorage(Class<T> clazz) {
        List<T> list = new ArrayList<T>();
        for ( ...whatever ...) {
           T obj = clazz.newInstance();
           // code to load from storage ...
           list.add(obj);
        return list;
    }And everything is fine except for one small gotcha. The argument to this method is a Class<T>, and what I read from my XML storage is the fully qualified name of my class(es). As you pointed out earlier, the Class.forName("Foo") method will return a Class<?> rather than a Class<Foo>. Therefore, I am still getting a compiler warning when attempting to produce the argument to pass to the loadFromStorage method.
    I was able to get around this problem and eliminate the compiler warning, but I'm not sure I like the way I did it. All of my persistent classes extend a common base class. So, I added a static Map to my base class:class Base
       private static Map<String, Class<? extends Base>> classMap = null;
       static
          Map<String, Class<? extends Base>> map = new TreeMap<String, Class<? extends Base>>();
          classMap = Collections.synchronizedMap(map);
       public static Class<? extends Base> getClass(String name)
          return classMap.get(name);
       protected static void putClass(Class<? extends Base> cls)
          classMap.put(cls.getName(), cls);
    }And added a static initializer to each of my persistent classes:class Foo extends Base
       static
          Base.putClass(Foo.class);
    }So now my persistence code can replace Class.forName("my.package.Foo") with Base.getClass("my.package.Foo"). Since Foo.class is of type Class<Foo>, this will give me the Class<Foo> I want instead of a Class<?>.
    Basically, it works and I have no compiler warnings, but it is unfortunate that I had to come up with my own mechanism to obtain a Class<Foo> object when my starting point was the string "my.package.Foo". I think that the JDK, in order to fully support reflection with generic types, should provide a standard API for doing this. I should not have to invent my own.
    Maybe it is there and I'm just not seeing it. Do you know of another way, using reflection, to get from a string "my.package.Foo" to a Class<Foo> object?
    Thanks again for your help,
    Gary

Maybe you are looking for

  • Create PDF files

    Does anyone know of a free software that creates PDF files that can be sent to a printer? I normally create them within QuarkXPress 8, however, when I upload them to the printer I get a message that the PDFs were not created in the latest PDF softwar

  • Floor Plan Manager - GAF configuration

    Hi Experts, In my application, I have only one WINDOW and three views. While configuring teh GAF, I get the option to enter the window name only. So I create three main steps. However while execute the application and click on main step2, it still sa

  • Bad Links - Download Oracle 10g

    Hi I am trying to download oracle 10g release 1 for Solaris (x86) from the link specified bellow. The problem is that I'm getting a file not found error for all the links on the page. http://www.oracle.com/technology/software/products/database/oracle

  • Constrained Nonlinear Curve Fit VI: Termination Revisited (LabVIEW 8.5)

    Hello: In the Constrained Nonlinear Curve Fit VI, the Help for the VI states that if the number of iterations exceeds max iterations specified in the termination control, the fitting process terminates. Would this not indicate that if the above condi

  • Unable to install oracle 10g

    Hi, I already had my 10g in my windows machine but it not installed properly,so I tryied to unistall and install my oracle 10 g in my machine. But while trying to uninstall i not found any unistall exe so i deleted the registered key,and again try to