List of custom objects as argument with generic method

java generic method parameter extends
java generic return type method example
implement generic interface java
arraylist generics java
java interface generic method
java generics wildcard
java method to accept any object
t in java example

I'm using generic methods in Java and I would like to use as argument a List of custom object.

My main class is this:

public class Main {

    public static <T> T executeGetRequest(String target, Class<T> resultClass) {

        //MY STUFF
        T result = resultClass.newInstance();
        return result;
    }

    public static void main(String[] args) {
        executeGetRequest("myList", List<myCustomObject>.class); // ERROR HERE
    }
}

I would like to use as argument a List<myCustomeObject>. When I'm using List.class, there is no error but I'm not sure that the result will be cast in a myCustomObject.


Code is very broken...

  1. List<myCustomObject>.class is wrong it can be only List.class

  2. List is an Interface and call of List.class.newInstance(); will throw an exception anyway

  3. Even if you will do code like:

    List<myCustomClass> myList = new ArrayList(); Object myResult = executeGetRequest("myList", myList.getClass());

You will get back myResult as instance of ArrayList class...

You need to reconsider what do you try to achieve - get back a List of myCustomClass objects or new instance of myCustomClass

BTW: at Runtime there is a "Type erasure" and there is no way to get what object types are in the List from List implementation.

In short at Runtime it is always List<Object>

Generic Methods (The Java™ Tutorials > Bonus > Generics), Consider writing a method that takes an array of objects and a collection and The compiler infers the type argument for us, based on the types of the actual  Recall that you cannot just shove objects into a collection of unknown type. The way to do deal with these problems is to use generic methods. Just like type declarations, method declarations can be generic—that is, parameterized by one or more type parameters. static <T> void fromArrayToCollection (T [] a, Collection<T> c) { for (T o : a) { c.add (o); // Correct } }


If you always return a list of items, then use List<T> as a return type:

public class Main {

    public static <T> List<T> executeGetRequest(String target, Class<T> resultClass) throws IllegalAccessException, InstantiationException {

        T item = resultClass.newInstance();
        List<T> result = new ArrayList<>();
        result.add(item);

        return result;
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        executeGetRequest("myList", Foo.class);
    }

    static class Foo {

    }

Java Generics Example Tutorial, To declare a bounded type parameter, list the type parameter's name, followed by the extends  A generic method is a method that is declared with type parameters, as follows: C#. static void Swap<T> (ref T lhs, ref T rhs) { T temp; temp = lhs; lhs = rhs; rhs = temp; } The following code example shows one way to call the method by using int for the type argument: C#.


Don't use a Class<T> argument, along with reflection (i.e. Class.newInstance()). Use a Supplier<T> instead:

public static <T> T executeGetRequest(String target, Supplier<T> factory) {

    // MY STUFF

    T result = factory.get();
    return result;
}

Then, invoke it as follows:

List<myCustomObject> result = executeGetRequest("myList", () -> new ArrayList<>());

You can even use the diamond operator (<>) when creating the ArrayList, as this is infered from the left hand side by the compiler (i.e. List<myCustomObject>).

You can also use a method reference:

List<myCustomObject> result = executeGetRequest("myList", ArrayList::new);

How to write generic classes and methods in Java, This Java Generics tutorial helps you design highly general and reusable as this class does its job well: persisting Student objects to database. Type parameters are never added to the names of constructors or methods. List; publicclassLibrary<T>{// "T" is the Type parameter. We can create Library of any Type. privateList<T>items;// represents the list of items of type we will pass. publicLibrary(List<T>items){. this.items=items; publicObjectissueItem(){. // write code to issue item. returnitems.get(0);


Java Programming Tutorial on Generics, A Java Collection (such as List and Set ) contains only objects. This method takes a Function object as argument and returns a generic type R . The generic  We generally use Collections.sort () method to sort a simple array list. However if the ArrayList is of custom object type then in such case you have two options for sorting- comparable and comparator interfaces. Before going through the example of them, let’s see what’s the output when we try to sort arraylist of Objects without


Java Generic Methods, In this case we are using two different types for T: String and Object . The compiler then uses the most specific type argument that makes the  The List<T> class is the generic equivalent of the ArrayList class. It implements the IList<T> generic interface by using an array whose size is dynamically increased as required. You can add items to a List<T> by using the Add or AddRange methods. The List<T> class uses both an equality comparer and an ordering comparer.


Java Reflection - Generics, Method object it is possible to obtain information about its public class MyClass { protected List<String> getActualTypeArguments(); for(Type typeArgument : typeArguments){ Class  The examples in this section use the generic List<T> class, which enables you to work with a strongly typed list of objects. The following example creates a list of strings and then iterates through the strings by using a For Each…Next statement. ' Create a list of strings.