Introducing generics to Java code without breaking the build
The following code does not compile:
public class GenericsTest {
public static void main(String[] args) {
MyList<?> list = new MyList<Object>();
Class<?> clazz = list.get(0);
// Does not compile with reason
// "Type mismatch: cannot convert from Object to Class"
MyList list2 = new MyList();
Class clazz2 = list2.get(0);
}
static class MyList<T> extends ArrayList<Class<T>> {
}
}
I wanted to do this to introduce generics to old code without breaking the build.
Is this a bug in both the compiler (both eclipse and javac) or am I missing something here? What other possibility exists to introduce generics to MyList?
EDIT
For clarification:
I have the generic class
public class MyList extends ArrayList<MyObject> {}
with
public class MyObject {}
and code using MyList
MyList list = new MyList();
...
MyObject o = list.get(0);
Now during development I see I want to introduce generics to MyObject
public class MyObject<T> {}
and now I want to have this new generic thingy in MyList as well
public class MyList<T> extends ArrayList<MyObject<T>> {}
But that does break my build. Interestingly
public class MyList<T> extends ArrayList<MyObject<T>> {
public MyObject<T> get(int i) {
return super.get(i);
}
}
will allow old code
MyList list = new MyList();
...
MyObject o = list.get(0);
to compile.
OK, seems that when I introduce this generic, I will have to live with having to change all calls to MyList to the generic form. I wanted the old code to just introduce a warning instead of an error.
Asked by: Charlie986 | Posted: 28-01-2022
Answer 1
I think you are not understanding quite how generics work.
MyList<?> list = new MyList<Object>();
Class<String> clazz= list.get(0);
This code snippet does not compile because you are telling the compiler that list
is going to hold Class<Object>
types - and then in the next line you are expecting it to return you a Class<String>
. The generic system in Java is not capable of converting types used with generics based on inheritance like you might think it would.
If you expect list
to hold Class<String>
, then you need to declare it as so - or, if you want it to be able to hold any types, then you cannot do the second line without a cast.
MyList<String> list = new MyList<String>();
Class<String> clazz = list.get(0);
or
MyList<?> list = new MyList<Object>();
//generates a warning about an unchecked cast
Class<String> clazz = (Class<String>) list.get(0);
The second code snippet does not work because when you use raw types, you still need to cast the Object
returned by get()
to the declared type you are using (which has always been the case).
MyList list2 = new MyList();
Class clazz2 = (Class) list2.get(0);
Answered by: Lydia165 | Posted: 01-03-2022
Answer 2
I don't have a compiler on this machine, but this should work.
public class GenericsTest {
public static void main(String[] args) {
MyList<Object> list = new MyList<Object>();
Class<?> clazz= list.get(0);
}
static class MyList<T> extends ArrayList<Class<? extends T>> {
}
}
Answered by: Max761 | Posted: 01-03-2022
Answer 3
In your example is MyList the old code you want to update to support generics? If so, what type of objects is my list supposed to contain?
As was mentioned here elsewhere that compilation error is valid. It is due to the fact that a raw list is being accessed without the get being cast to Class. Hence the code is attempting to assign an Object to a reference of a Class. It is equivalent to this:
Object o = new Object();
Class c = o;
Which simply cannot compile. Also, to fully utilize generics you should favor Class<?> instead of Class.
Answered by: Aston621 | Posted: 01-03-2022Answer 4
In your example the second example doesn't work because you are not using generics so it means that the get() method will return a Object and you will need to cast it to a Class. When you are not specifying a type for your MyList :
MyList list2 = new MyList();
Then you are losing the Generics advantages and you need to cast the object when calling the get() method just like in the good ol' days.
Answered by: Walter332 | Posted: 01-03-2022Answer 5
Have you tried:
Class clazz2 = list2.get(0).getClass();
Read about it at: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#getClass()
Answered by: Julian410 | Posted: 01-03-2022Similar questions
java - Introducing Spring MVC
I'd like to introduce Spring MVC to an application that has up till now used simple direct access to JSP files i.e www.example.com/login.jsp which contains the business logic and presentation details.
I'd like to strip out the business logic and keep only the presentation in the JSP. To do this, I've moved the jsp file from webapp/login.jsp to webapp/WEB-INF/jsp/login.jsp and ...
java - Introducing Ajax support in a MyFaces (JSF) + Tomahawk application
we have a project where we are using MyFaces + Tomahawk, recently I have been requested to provide enhancements to many of the existing screens by using AJAX and provide functionality such as partial refresh. As I see, Tomahawk's components don't have special support for Ajax, so it may be a lot of work to hack Tomahawk in order to use Ajax.
Now, I have seen that t...
Introducing scala into existing netbeans java project
I have an existing java project in Netbeans. I would like to start coding parts of it in Scala. I can add ".scala" files to the project but apparently they aren't compiled.
Can I somehow modify the existing Netbeans project settings in order to build java and scala sources together or do I need to create a new project and import the existing (java) sources?
Thanks
Martin
EDIT
java - Tutorial for introducing someone to OOP
java - How to allow introducing only digits in jTextField?
I have tried to use the example shown here but java showing error message of
"AttributeSet cannot be resolved to a type"
That is why I am trying to use another method of allowing only digits:
txtUsername.addKeyListener(new MyKeyListener());
public class MyKeyListener extends KeyAdapter{
public void keyP...
swing - Introducing just numbers form an interval in a TextField in Java
How can I add just numbers betwwen 0 and 255 in a FormattedTextField in Java?
I tried this way :
private JFormattedTextField text4;
//...
text4= new JFormattedTextField(paymentFormat);
text4.getValue();
text4.setColumns(3);
try {
MaskFormatter mask = new MaskFormatter("###");
mask.install(text4);
} catch (ParseException ex) {
System.out.print("Valoarea nu e cor...
java - Using guava Function interface vs introducing new types
When I write some API I try to avoid introducing new interfaces, and often this makes me want to use the guava interface "Function". For example rather than doing:
// a new interface
interface URILookup {
public URI lookup(Object o);
}
public class Some {
public Some(URILookup u){//...}
}
I replace URILookup with Function<Object,URI> and document the us...
java - Introducing dependency breaks existing dependency?
I'm working on a project that builds and deploys fine. I'm trying to add some code that uses JWebUnit, and use the following Maven code to bring it in:
<dependency>
<groupId>net.sourceforge.jwebunit</groupId>
<artifactId>jwebunit-htmlunit-plugin</artifactId>
<version>3.2</version>
<scope>test</scope>
</dependency>
java - Could I have some guidance on introducing methods into my wages program?
I am a little stuck. I have grasped the concept of methods; understanding their purpose but still unsure on how to code it. Below is part of my code I kindly need guidance on. I am trying to create a method which can hold roles and depending on which switch option is selected it will return the the amount. I have four employment roles which all have different payscales. I have commented the errors on the role method. If I ...
Introducing new statements in java syntax
Is there a through which we can add new statement to java syntax like if i write the line
add(6)(5)(4)(3)
i get the answer 18
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)