The parameter is ArrayList and how can I get the T's className

The parameter is ArrayList<T> how can I get the T's className

public static <T extends Object> void test(ArrayList<T> list){ T temp; Class classType=temp.getClass(); System.out.println(classType.getName()); }

It will be failed to compile that:he local variable temp may not have been initialized.

But how can I get the className of the template class.

-------------Problems Reply------------

You cannot get the generic type. This is due to how generics are implemented in Java (using type erasure). Basically, you can only use generics to catch type-errors at compile-time.

Your code fails to compile, because you are trying to call getClass on a local variable that has not been initialized.

What you could do instead is:

  • pass in a Class<T> parameter in addition to the list to tell the method about the type to be used
  • or look at the first element of the list (if present) and trust that its runtime type is representative enough (which it may not)

You cannot, because of type erasure in the implementation of Java generics. When you need to know the class, the typical trick is to pass Class as a separate parameter called "type token", like this:

public static <T extends Object> void test(ArrayList<T> list, Class<T> classType) {

This trick is discussed at some length in the tutorial on Java generics (see the bottom of the page for an example).

It seems you can with little wrapping your 'T' or Eraser. Here is SO discussion related to this. Get instance of generic type

You can try this work around:

public static <T extends Object> void test(ArrayList<T> list){
if(null!=list && !list.isEmpty())

Category:java Views:0 Time:2012-01-06
Tags: java generics

Related post

  • Pass An ArrayList to a function that accepts as parameter an ArrayList in Java 2012-04-10

    I am writing a generic java-android function that will accept as one of it's parameters an ArrayList<Object>, so that I can use all over my application regardless of the type of the ArrayList elements. This is my function: public GenericDisplay

  • How to clone ArrayList and also clone its contents? 2009-04-03

    How can I clone ArrayList but also clone its items in Java 1.5? For example I have: ArrayList<Dog> dogs = getDogs(); ArrayList<Dog> clonedList = ....something to do with dogs.... And I would expect that objects in clonedList are not the s

  • How do I pass an ArrayList to a method expecting a vararg (Object-)? 2011-01-15

    Assume a method with the following signature: public static void foo(String arg1, String args2, Object... moreArgs); When running ..."something", "something", "first", "second", "third"); ... I'll get moreArgs[0] == "first", moreArgs[1

  • using toArray with ArrayList of custom objects 2011-11-16

    Is there a way to use the toArray() method on an ArrayList<CustomObject>? From what I see, it can only be used with Object --------------Solutions------------- You need to pass in an array of CustomObject in order to get one back. The parameter

  • how to create an ArrayList to generate from 0 to 255? 2011-12-08

    I am using Java/Eclipse. I don't understand/know how to put these two codes together to answer the following questions: Create a method RandomArray that takes in as parameter an integer n and returns a ArrayList of Integers (ArrayList<Integer>)

  • Initializing an ArrayList within a constructor 2014-01-31

    As part of an assignment I'm supposed to create a bunch of rectangles and put each of those objects within an ArrayList, which is to be initialized in a constructor. I think I've confused myself. Eclipse is telling me that I can't use .add(new_rec) w

  • onerror parameter in ant / in antlib descriptor 2009-10-11

    I am creating an antlib with custom tasks to be used in our build system. I have looked at antcontrib antlib declaration and noticed that the typedefs/taskdefs have onerror parameter set to ignore, e.g. <taskdef name="for" classname="net.sf.antcon

  • Django return HttpResponseRedirect to an url with a parameter 2010-06-29

    I have a situation in my project where i need to make a redirection of the user to an url containing a parameter, (it is declared in the like: url(r'^notamember/(?P<classname>\w+)/$', notamember, name='notamember'),) How can i put that

  • why cannot access arraylist from other class? 2012-05-01

    In webservice class, it will retrieve database from online and put into list: public List<List_NewsComment> allCommentList; public void GetCommentNews( final int gCommentNewsID) { Thread networkThread=new Thread(){ @Override public void run(){

  • Using Java generics in interfaces that return collections. Best practice? Pitfalls? 2010-02-10

    I ran into some code today that I found questionable. Here's a simplified example (not realistic). public interface IListable { //returns first n items from list public ArrayList getFirstNThings(int n); //returns last n items from list public ArrayLi

  • Is there a way to implement a core code template in WCF? 2010-02-11

    I am working on a WCF based web services project. We have like 50 different services which provide get,create, update and delete operations. My problem is when I find a bug in an operation, let's say in get operation, that is common on all the servic

  • Taming the type checker in Java Generics 2010-08-10

    I thought I understood Generics pretty well, but apparently I didn't. Here is the test case of the problem: import java.util.ArrayList; class Job<J extends Job<J,R>, R extends Run<J,R>> {} class Run<J extends Job<J,R>, R ex

  • Invalid attempt to Read when reader is closed 2011-04-01

    I'm working on C# and MySql request. I'm trying to retrieve my datas in my db but I have this error message : Invalid attempt to Read when reader is closed. Thanks for your help guys :) I have this function : public MySqlDataReader GetValueFromTable(

  • Making generic calls with JAVA JNI and C++ 2011-04-12

    I am working with JNI and I have to pass in some generic types to the C++. I am stuck with how to approach this on the C++ side HashMap<String, Double[]> data1 ; ArrayList<ArrayList<String>> disc ; I am new to JNI and looked around

  • Using regex to access items in a List 2011-07-29

    Possible Duplicate: Search for a regexp in a java arraylist Is there a way to access items stored in a List using regular expressions? Take the following code as an example: String jpg = "page1.jpg"; String jpeg = "page-2.jpeg"; String png = "page-00

  • What's th mean by "public abstract class SampleAdapter extends ViewGroup"? 2011-08-03

    I am not getting meaning by public abstract class SampleAdapter <T extends Adapter> extends ViewGroup What does it do? In general we perform normal inheritance, but here something extended form. can any body suggest me? thanks --------------Sol

  • Trouble calling a superclass method from inside a subclass static method 2011-09-19

    I have a class Mouse that extends the class Mammal. In Mouse, I have a static method which takes in as parameter an ArrayList of Mouse objects, like this: public static void mate(ArrayList<Mouse> mice) Inside this static method, I have this lin

  • 'dynamic'-like java annotations? 2011-09-28

    I have a pojo that is dependent on annotations. It has predefined fields as well as a Set that contains user provided fields: public class MyPOJO implements Document { private String id; private LocalString name; private LocalString desc; private Lis

  • Delay property on Binding from .Net 4.5 in .Net 4.0 2011-10-05

    How can I implement Delay property from .Net 4.5 (described here) on binding in .Net 4.0? I know I cannot inherit from BindingBase as ProvideValue is sealed. I could implement MarkupExtension but it means I now have to rewrite all properties from Bin

Copyright (C), All Rights Reserved.

processed in 0.092 (s). 11 q(s)