This is not a question how to do things. It is a question of why is it the way it is.
Arrays in Java know their component type at run time, and because of type erasure we cannot have array objects of generic type variables. Array types involving generics are allowed and checked for sound read/write, the only issue seem to be the allocator expressions.
Notice that the Java compiler also disallows the following:
Pong<Integer> lotsofpong [] = new Pong<Integer>[100];
...where Pong is just any old parametric class. There is nothing unknown here. Yes, at run-time, lotsofpong would just be an array of Pong, but I cannot see a reason why the compiler cannot remember the type parameter for compile-time purposes. Well, it actually does remember it, because those types exist at compile time, so the only problem seems to be the refusal to give the allocator at compile-time a particular generic-parameter-involving component type.
Even if the parameter of Pong was a generic type variable that should not make a difference either. The dynamic array would still be an array of Pong, requiring per element the size of a Pong, which does not depend on its type parameter.
Yes, I know there are ways around it - either use casts (perhaps with SuppressWarning) from the non-parametric type, or subclass Pong<Integer> with a non-parametric class and use that type instead. But is there a reason why this kind of allocator is not allowed?
Based on the link that was provided by Zeller (based on Josh Bloch - 'Effective Java Book').
Arrays are not safe because the following code will compile:
String strings [] = {"Foo"};
Object objects [] = strings;
objects[0] = 1;
You will get a special exception at run-time: java.lang.ArrayStoreException.
Java run-time cheks at run-time that you put an appropriate type into the array.
Assigning an array to an array of its super type is called 'Covariance'.
Generics are guaranteed to be safe at compile-time.
If the code snippet that you mentioned in the question was able to be compiled, the following code would also compiles:
Pong<Integer> integerPongs [] = new Pong<Integer>[100];
Object objectPongs [] = integerPongs;
objectPongs[0] = new Pong<String>();
Pong<Integer> stringPong = integerPongs[0]; // ClassCastException
Our code becomes not safe therefore it was forbidden by the specification.
The reason that :
objectPongs[0] = new Pong<String>();
does not throw java.lang.ArrayStoreException is because the run-time type of each instance of Pong is always Pong since Generics is a compile-time mechanism.
Related
I am wondering how can I get the runtime type which is written by the programmer when using generics. For example if I have class Main<T extends List<String>> and the programmer write something like
Main<ArrayList<String>> main = new Main<>();
how can I understand using reflection which class extending List<String> is used?
I'm just curious how can I achieve that. With
main.getClass().getTypeParameters()[0].getBounds[]
I only can understand the bounding class (not the runtime class).
As the comments above point out, due to type erasure you can't do this. But in the comments, the follow up question was:
I know that the generics are removed after compilation, but I am wondering how then ClassCastException is thrown runtime ? Sorry, if this is a stupid question, but how it knows to throws this exception if there isn't any information about classes.
The answer is that, although the type parameter is erased from the type, it still remains in the bytecode.
Essentially, the compiler transforms this:
List<String> list = new ArrayList<>();
list.add("foo");
String value = list.get(0);
into this:
List list = new ArrayList();
list.add("foo");
String value = (String) list.get(0); // note the cast!
This means that the type String is no longer associated with the type ArrayList in the bytecode, but it still appears (in the form of a class cast instruction). If at runtime the type is different you'll get a ClassCastException.
This also explains why you can get away with things like this:
// The next line should raise a warning about raw types
// if compiled with Java 1.5 or newer
List rawList = new ArrayList();
// Since this is a raw List, it can hold any object.
// Let's stick a number in there.
rawList.add(new Integer(42));
// This is an unchecked conversion. Not always wrong, but always risky.
List<String> stringList = rawList;
// You'd think this would be an error. But it isn't!
Object value = stringList.get(0);
And indeed if you try it, you'll find that you can safely pull the 42 value back out as an Object and not have any errors at all. The reason for this is that the compiler doesn't insert the cast to String here -- it just inserts a cast to Object (since the left-hand side type is just Object) and the cast from Integer to Object succeeds, as it should.
Anyhow, this is just a bit of a long-winded way of explaining that type erasure doesn't erase all references to the given type, only the type parameter itself.
And in fact, as a now-deleted answer here mentioned, you can exploit this "vestigial" type information, through a technique called Gafter's Gadget, which you can access using the getActualTypeArguments() method on ParameterizedType.
The way the gadget works is by creating an empty subclass of a parameterized type, e.g. new TypeToken<String>() {}. Since the anonymous class here is a subclass of a concrete type (there is no type parameter T here, it's been replaced by a real type, String) methods on the type have to be able to return the real type (in this case String). And using reflection you can discover that type: in this case, getActualTypeParameters()[0] would return String.class.
Gafter's Gadget can be extended to arbitrarily complex parameterized types, and is actually often used by frameworks that do a lot of work with reflection and generics. For example, the Google Guice dependency injection framework has a type called TypeLiteral that serves exactly this purpose.
Using Java's Generics features I created a List object and on the left hand side I am using the raw type List where on the right hand side I am using the generic type ArrayList< String >.
List myList=new ArrayList<String>();
And I added one int value into the list object.
myList.add(101);
I was hoping that I will get some compilation error but this program is running fine.But if I use generic type List< String > on the left hand side and raw type ArrayList on the right hand side and try to add an int value into the list, I am getting compilation error as expected.
List<String> myList=new ArrayList();
myList.add(101);//The method add(int, String) in the type List<String> is not applicable for the arguments (int)
Why in Java generics right hand side type of the collection does not have any effect? And why Java allowing us to do so when it does not have any effect.I am using Java 1.6. Please explain.
If you don't supply a generic type parameter on the left-hand side, the List is declared as a raw type. This means the compiler doesn't know what is legal or not to store in that list, and is relying on the programmer to perform appropriate instanceof checks and casts.
Raw types also have the effect of obliterating all generic type information in the class they appear in.
The JLS provides a much more detailed look at raw types. You should be seeing a warning in your IDE or from the compiler about the assignment to a raw type as well:
To make sure that potential violations of the typing rules are always
flagged, some accesses to members of a raw type will result in
compile-time unchecked warnings. The rules for compile-time unchecked
warnings when accessing members or constructors of raw types are as
follows:
At an assignment to a field: if the type of the left-hand operand is a
raw type, then a compile-time unchecked warning occurs if erasure
changes the field's type.
At an invocation of a method or constructor: if the type of the class
or interface to search (§15.12.1) is a raw type, then a compile-time
unchecked warning occurs if erasure changes any of the formal
parameter types of the method or constructor.
No compile-time unchecked warning occurs for a method call when the
formal parameter types do not change under erasure (even if the result
type and/or throws clause changes), for reading from a field, or for a
class instance creation of a raw type.
Tom G's answer is nice and explains things in detail, but I get the feeling that you already know at least some of that stuff, because you said this:
I was hoping that I will get some compilation error
So, let me address precisely that part.
The reason you are not getting any compilation error is because generics were added as an afterthought in java, and for this reason many generics-related issues which ought to be errors have instead been demoted to warnings in order to not break existing code.
And what is most probably happening is that these warnings are turned off in your development environment.
Steps to correct the problem:
Go to the options of your IDE
Find the "warnings" section.
Enable EVERYTHING.
Pick your jaw from the floor after you have seen the enormous number
of warnings you get.
Disable all the warnings that do not make any sense, like "hard-coded string" or "member access was not qualified with this", keep everything else. Be sure that the one which says something like "Raw use of parameterized class" is among the ones you keep.
At a glance it looks like myList can only store String
At a glance, perhaps. But it's really important to realize that there is no such thing as "a list that can only store Strings", at least in the standard APIs.
There is only List, and you have to include the right instructions to the compiler to berate you if you try to add something that's not a String to it, i.e. by declaring it as List<String> myList.
If you declare it as "plain old List", the compiler has no instructions as to what to allow or disallow you to put into it, so you can store anything within the type bounds of the backing array, namely, any Object.
The fact that you say new ArrayList<String>() on the RHS of the assignment is irrelevant: Java doesn't attempt to track the value assigned to a variable. The type of a variable is the type you declare.
"... generics right hand side of type of the collection does not have any effect" is mostly true. When the "var" keyword is substituted for "List", the right hand side generic does have an effect. The code below creates an ArrayList of Strings.
var myList = new ArrayList<String>();
I recently came across that, Arrays are reified in Java. That is, they know the type information only during run time. But I am a little confused with this definition.
If Arrays are said to know the type information only during runtime, I should literally be able to assign any values to any arrays, since the typing is known only at run time and errors will be thrown at run time only. But that is not the case in real time. We get a compile time error for that.
So can someone throw light on "what does it mean by - arrays are reified"?
What I think that means is that the given lines of code will throw an exception:
String[] arrayOfStrings = new String[10];
Object[] arrayOfObjects = arrayOfStrings; // compiles fine
arrayOfObjects[0] = new Integer(2); // throws a runtime exception (ArrayStoreException IIRC)
Arrays are covariant: String[] extends Object[]. But the actual type of the array is known at runtime, and an attempt to store an instance which is not of the right type throws an exception.
I believe the term you are looking for is reifiable.
A reifiable type does not lose any type information due to type erasure at runtime. Examples of reifiable types include:
primitives
non-generic reference types
arrays or primitives or arrays
of non-generic reference types.
Reifiable does not mean a type is not known at compile time. What this does mean is that something like the following, cannot be typed checked:
List<Integer>[] myList;
Arrays carry runtime information about the types they store. Non-refiable types cannot be type checked at runtime, which does not make them good candidates for the component type of an array.
When using reifiable types as the component type of an array such as String[] the complete type information is available at runtime, so type checks can be performed.
String[] someArray = new String[2];
//some factory returns Integer upcasted to Object
someArray[0] = someFactory.getType("Integer"); //throws RuntimeException
Sources:
http://docs.oracle.com/javase/tutorial/java/generics/nonReifiableVarargsType.html
http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ106 (Good)
If Arrays are said to know the type information only during runtime, I should literally be able to assign any values to any arrays, since the typing is known only at run time errors will be thrown at run time only. But that is not the case in real time. We get a compile time error for that.
Reifiable types know their type at runtime and compile time, which is why the compiler will still prevent you making silly mistakes where it can (what's the point in letting them through?)
However, there's times when the compiler can't always work out for certain whether an assignment (for instance) will be valid because it doesn't know the exact types, and this is where reified types can check. For instance:
Object[] arr = new String[5];
arr[0] = 7;
...this will compile, because on the second line the compiler only knows the static type of the array as Object, whereas the dynamic type is something more specific. It will fail as an exception at Runtime, which it can only do because (unlike with the generic collection classes) the specific type is known at runtime.
As mentioned in doc:
A reifiable type is a type whose type information is fully available
at runtime. This includes primitives, non-generic types, raw types,
and invocations of unbound wildcards.
Non-reifiable types are types where information has been removed at
compile-time by type erasure — invocations of generic types that are
not defined as unbounded wildcards. A non-reifiable type does not have
all of its information available at runtime. Examples of non-reifiable
types are List and List; the JVM cannot tell the
difference between these types at runtime. As shown in Restrictions on
Generics, there are certain situations where non-reifiable types
cannot be used: in an instanceof expression, for example, or as an
element in an array.
So Arrays are reified and covariant but generics are invariant and type-erased by nature. Arrays provide runtime type safety and throw ArrayStore exception if element of correct type is not added.
What is the difference between compile time and run time type of any object in Java ? I am reading Effective Java book and Joshua Bloch mentions about compile time type and run time types of array instances in Item 26 many times mainly to describe that suppressing cast warnings can be safe sometimes.
// Appropriate suppression of unchecked warning
public E pop() {
if (size == 0)
throw new EmptyStackException();
// push requires elements to be of type E, so cast is correct
#SuppressWarnings("unchecked") E result = (E) elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
Here the author is talking about these different types of types in context of arrays . But through this question I would like to understand the difference between compile time types vs run time types for any type of object .
Java is a statically typed language, so the compiler will attempt to determine the types of everything and make sure that everything is type safe. Unfortunately static type inference is inherently limited. The compiler has to be conservative, and is also unable to see runtime information. Therefore, it will be unable to prove that certain code is typesafe, even if it really is.
The run time type refers to the actual type of the variable at runtime. As the programmer, you hopefully know this better than the compiler, so you can suppress warnings when you know that it is safe to do so.
For example, consider the following code (which will not compile)
public class typetest{
public static void main(String[] args){
Object x = args;
String[] y = x;
System.out.println(y[0])
}
}
The variable x will always have type String[], but the compiler isn't able to figure this out. Therefore, you need an explicit cast when assigning it to y.
An example
Number x;
if (userInput.equals("integer")) {
x = new Integer(5);
} else {
x = new Float(3.14);
}
There are two types related to x
the type of the name x. In the example, it's Number. This is determined at compile-time and can never change, hence it's the static type
the type of the value x refers to. In the example, it can be Integer or Float, depending on some external condition. The compiler cannot know the type at compilation time. It is determined at runtime (hence dynamic type), and may change multiple times, as long as it's a subclass of the static type.
Java is statically typed. That means that every expression (including variables) in the language has a type that is known at compile time according to the rules of the language. This is known as the static type (what you call "compile-time type"). The types in Java are the primitive types and the reference types.
Also, each object at runtime in Java has a "class" (here, "class" includes the fictitious array "classes"), which is known at runtime. The class of an object is the class that an object was created with.
Part of the confusion comes from the fact that each class (and interface and array type) in Java has a corresponding reference type, with the name of the class (or interface or array type). The value of a reference type is a reference, which can either be null or point to an object. The Java language is designed so that a reference of reference type X, if not null will always point to an object whose class is the class X or a subclass thereof (or for interfaces, whose class implements the interface X).
Note that the runtime class applies objects, but objects are not values in Java. Types, on the other hand, apply to variables and expressions, which are compile-time concepts. A variable or expression can never have the value of an object, because there are no object types; it can have a value of a reference that points to an object.
I think of "compile time type" as ANY type a variable can be shown to have at compile time. That would include the declared class, any superclasses, and any implemented interfaces.
At runtime, a given object only has one lowest-level class; it can legally be cast to or assigned to a variable of that class, but also to any variable of any of its subclasses or implemented interfaces. The compiler will (often, anyway) allow you to cast it to anything, but the runtime will throw an exception if you attempt to assign something that is not legal.
Once an object is assigned to the variable, then the compiler will treat it as though it is of the type of the variable. So another use of "compile time" could be the variable type, and you can get around that at compile time by casting to a different type as long as you know the cast will be legal at runtime.
If I speak of just one type, I think of the 'runtime type' of a variable as the actual bottom (top?) level subclass of the variable; the lowest sub-class to which it could be cast. But I also routinely think of any object as an instantiation of any of its legal types.
Hope that helps.
Java arrays are so called "covariant", which means a String[] is a subtype of Object[], and type rules are checked at COMPILE time.
Java arrays check at RUNTIME if the object (e.g. String, Integer, WhatEver) you would like to store into it, is compatible with the type the array actually created with.
For example:
String[] strings = new String[2];
strings[0] = "I am text";
Object[] objects = strings;
objects[1] = new Date(); // Compiles, but at runtime you get an ArrayStoreException
I'm quite new to Java (and english), so please bear with me.
Tried to write something like...
Container con = new Container<Book>();
con.insert(new Book());
con.insert(new Car());
...and did not get any type of error. But lines like...
Car c = con.remove(); // removes the last inserted element for simplicity
said "error: incompatible types", so I changed it to
Object carObj = (Car) con.remove();
and it worked. My problem is: when I say
new Container<Book>();
I create a container that can only hold objects of type Book, but because of the pointer (which is non-generic?) I can suddenly put any kinds of objects in my container. What happened here? The pointer only sees the Object-personality in whatever is in the Container, but I didn't know the pointer allowed every object with Object-personality in a container mainly created as generic (my formulation might be wrong). So when I have a non-generic pointer, it doesn't matter whether I create a generic or non-generic container? It will always be considered as a non-generic container (where I have to cast objects when I remove them)?
new Container<Book>().insert(new Car()); // compiler error as excepted
Got curious and made the problem even worse (maybe).
Container<Car> cars = new Container();
cars.insert(new Book()); // compiler error: required Car, found Book
Now the pointer only sees the Car-personalities in the container. But it won't allow me to put in a book even though I created the container as non-generic. Why?
new Container().insert(new Car()); // works fine
Must say, it's both fascinating and irritating...
You're operating on the reference: the reference's type is what will be used at compile time. Inserting a Book into a Container<Car> is clearly wrong, just as there's nothing wrong with inserting either a Book or a Car into a Container.
Similarly, expecting a Container.remove to return a Car when the reference is simply <Container> is incorrect, because there's no reason to expect the returned object to be a Car–it might be a Book or a fish.
Your container is a raw container and not a generic container. It's declared as Container. It should be declared as Container<Book>.
Once done, the line
con.insert(new Car());
won't compile anymore.
In Java, the generic type of an object is only a compile-time thing. At runtime, due to erasure, it's just a Container. So if you don't declare the container as a Container<Book>, you'll have a raw Container and the compiler won't check anything about the type of objects you store inside.
To make it clearer (at least I hope so), the line
Container con = new Container<Book>();
is equivalent to
Container con = (Container) (new Container<Book>());
It transforms a reference to a Container<Book> into a reference to a raw Container, ruining its type-safety.
Java added generics after there was already lots of code written without generics. The designers of generics wanted to change standard library containers like List into List<X>, but there was already lots of code written to take just plain List that would no longer compile if they'd required all uses to become List<X> uses. Furthermore, they wanted people using legacy libraries of their own that, for instance, asked for a List and expected it to contain only String instances to be able to pass in a List<String>.
The way they dealt with this was to introduce the notion of a "raw type" for every generic type, which is basically just the type you get by not writing the angle brackets after a generic type (e.g. List instead of List<String>). Raw types have different type-checking rules then their non-raw equivalents; for instance if you have a List then it's legal to add any Object into it, but when you get something back it comes back as an Object that you need to downcast, whereas a List<String> will only allow you to add a String, but in return you don't need to downcast get's result to get a String back.
Unfortunately, due to the backwards-compatibility rule that the language designers made, they allowed you to write expessions like
List rawList = new ArrayList<String>();
rawList.add(new PeanutButterSandwich());
without a compile-time error. You can even do worse things, like
List<String> stringList = new ArrayList<String>();
stringList.add("string");
List rawList = stringList;
List<PeanutButterSandwich> sandwichList = (List<PeanutButterSandwich>) rawList;
PeanutButterSandwich sandwich = sandwichList.get(0);
which compiles (with a warning about an unchecked cast, meaning you made a cast to a generic type from a raw type but the compiler doesn't know that it's legal). Of course this code will definitely raise an exception at runtime since the element in position 0 is a String, not a PeanutButterSandwich.
What's important to remember is that raw types are only for backwards compatibility, and you shouldn't use them in new code. Also, if you're ever dealing with raw types, be very careful when casting them to generic types, since the compiler can't stop you from doing wrong things.