[PDF] [PDF] Generics in Java Generic types are erased by





Previous PDF Next PDF



Cours 10 : Type générique

Java depuis la version 1.0. - permet d'écrire du code plus sûr et plus facile à lire qu'un code parsemé de variables Object 



Programmation Objet Java–Classes Génériques

Classe générique (Generic class) : une classe dont la définition est paramétrée avec un ou plusieurs types « variables ». class Stack <T> { void push(T o){.



Generics (in Java)

5. Recently : push for simplifying/eliminating wildcards!!! Page 4. 1 A Generic Swap: in different languages template <class T>.



Types paramétrés

Generics de Java. ? Pour : – Le code du generic est vérifié à compile time lors de sa définition. – Le compilateur transforme le code générique en code.



A Generic Type-and-Effect System

24 janv. 2009 Effect systems have recently been used to enforce a locking discipline to prevent race conditions in. Java (Flanagan and Freund 2000; Abadi et ...



Generics in the Java Programming Language

16 févr. 2004 In the introduction we saw invocations of the generic type declaration List



Safe instantiation in Generic Java

The Safe Instantiation Principle: Instantiating a generic class with types that meet the declared constraints on the parameters should not generate any type 



Global Type Inference for Featherweight Generic Java

We study global type inference for Featherweight Generic Java (FGJ) a functional Java core language. Given generic class headers and field specifications



Efficient Implementation of Run-time Generic Types for Java

Java which does not support run-time generic types. Our implementation of. NextGen consists of a compiler extending the GJ compiler and a special class.



Efficient Implementation of Run-time Generic Types for Java

Java which does not support run-time generic types. Our implementation of. NextGen consists of a compiler extending the GJ compiler and a special class.



[PDF] Java Generics

You can define your own class as a generic class The class definition code is parameterized by a type typically called This is more or less what 



[PDF] Generics in the Java Programming Language - Oracle

5 juil 2004 · A generic type declaration is compiled once and for all and turned into a single class file just like an ordinary class or interface 



[PDF] Java Generics

Java generics are realized by mapping parametric genericity to inheritance genericity – The compiler removes all type parameters / arguments



[PDF] Java - Generics - Tutorialspoint

A type parameter also known as a type variable is an identifier that specifies a generic type name The type parameters can be used to declare the return type 



[PDF] JAVA GENERICS - Cornell Computer Science

Early versions of Java lacked generics Proposals for adding Generics to Java Java's type system allows the analogous rule for arrays:



[PDF] Generics in Java

Generic types are erased by type erasure in the compiled program ? At runtime there exist only one http://java sun com/j2se/1 5/ pdf /generics-tutorial pdf



[PDF] Generics (in Java)

Java generics simply provide compile-time type safety and eliminate the need for casts Generics use a technique known as type erasure as described above 2013 



[PDF] Java et Généricité - FR

One of the new features of Java 1 5 are the Generics They allow us to abstract over types and help us to write type safe code The generics are in some aspects 



[PDF] Generics in Java - BVRIT Hyderabad

The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects It makes the code stable by detecting the bugs at compile time Before 



[PDF] Java Generics - Department of Computer Sciences

Generics class can be instantiated only with classes (not primitive types) However autoboxing and unboxing of primitive types make generics act as if they

:
Generics in JavaMarc Framvig-Antonsen & Jens Svensson

 Introduced in JDK1.5 Classes, Class methods and Interfaces can be generic Generic types are erased by type erasure in the compiled program At runtime there exist only one implementation of the generic code(class,method,interface) Multiple generic parameters Wildcard generics arguments. Bounding generic parameter both upper and lower Default upper bound is Object. Type correctness is checked at compile time, using the upper bound of the generic parameters

public class Holder { private T value; public Holder(T a_value){ value=a_value; public T getValue(){ return value; }Generic class Holder h=new Holder("String");

Holder hi=new Holder(45);

System.out.println(h.getValue());

System.out.println(hi.getValue());

System.out.println(h.getClass());

System.out.println(hi.getClass());

Output

Generic parameters come after the name of the class The class of the variables h and hi are Holder. Generic Classes don't infer types from constructor arguments. Have to specify the type two places The code of the class must valid for the bound of the generic parameterUsageString

45
class Holder class Holder public class _2Parameters{

T value1;

P value2;

public _2Parameters(T a_value,P a_value2){ value1=a_value; value2=a_value2; } public T first(){ return value1; public P second(){ return value2;

}Generic class multiple generic parameters _2Parameters _2par=new _2Parameters("test",45);

System.out.println(_2par.first());

System.out.println(_2par.second());

Output

 The Generic Parameter list is comma separated.Usagetest 45
class Throwable_1 extends Throwable{

}Generic classes may not be direct or indirect subclass of ThrowableThrowable_1 Test=m.new Throwable_1();

OutputUsage The catch mechanism only works with non generic types Exception in thread "main" java.lang.Error: Unresolved compilation problem:

The generic class Main.Throwable_1 may not subclass java.lang.Throwable at Main$Throwable_1.(Main.java:78) at Main.main(Main.java:93) public class Normal{ public void printValue(Holder a_value){ System.out.println("In Normal Class:"+a_value.getValue()); }Generic method Normal n=new Normal(); n.printValue(hi); n.printValue(h);

Output

 Generic Paremeters comes after scope but before return value of the method Generic Methods do infer the generic types from passed values.UsageIn Normal Class:45

In Normal Class:String

public class Normal{ public void printValue(T a_value){ System.out.println("In Normal Class:"+a_value.getValue()); } }Generic method Normal n=new Normal(); n.printValue(hi); n.printValue(h); OutputUsageException in thread "main" java.lang.Error: Unresolved compilation problem:

The method getValue() is undefined for the type T

at Normal.printValue(Normal.java:6) at Main.main(Main.java:91)

 The Generic Parameter T is unbounded so it defaults to Object. Object don't have a getValue function It does not matter that we only send objects of Holder to it

Effects of Type Erasure

public class Normal{ public void printHolder(Holder a_value){ System.out.println("In Normal Class:"+a_value.getValue()+" Its a string"); } public void printHolder(Holder a_value){ System.out.println("In Normal Class:"+a_value.getValue()*10);

}Generic method Overloading The Generic arguments and are both removed in the compiled code so the 2 functions are identical.Output

Exception in thread "main" java.lang.Error: Unresolved compilation problems: Duplicate method printHolder(Holder) in type Normal Duplicate method printHolder(Holder) in type Normal public class Normal{ public void printHolder(Holder a_value){

System.out.println("In Normal Class:"+a_value.getValue()+" Its a string"); } public int printHolder(Holder a_value){

System.out.println("In Normal Class:"+a_value.getValue()*10); return 0; } }Generic method Overloading on return type Normal n=new Normal(); n.printHolder(hi); n.printHolder(h);

OutputUsageIn Normal Class:450

In Normal Class:String Its a string

 The correct method gets called. Has to return a value public class Normal{ public void printHolder(Holder a_value,String dummy){

System.out.println("In Normal Class:"+a_value.getValue()+" Its a string"); } public void printHolder(Holder a_value,Integer dummy){

System.out.println("In Normal Class:"+a_value.getValue()*10); }Generic method Overloading on dummy parameter Normal n=new Normal(); n.printHolder(hi,new Integer(42)); n.printHolder(h,new String(""));

OutputUsageIn Normal Class:450

In Normal Class:String Its a string

 The correct method gets called. Has to send in a dummy value

public class Specialisation{} public class Specialisation{} Only one generic class The type erasure erases the type parameters, and there can't be 2 implementations of the same type.

public class StatTest { private static int id=0; public StatTest(){ id++; public int getId(){ return id; }Shared static members StatTest s1=new StatTest();

StatTest s2=new StatTest();

System.out.println(s1.getId());

System.out.println(s2.getId());

OutputUsage2

2

 The field id are static and are therefore shared by all instances of StatTest. The Generics are type erased so eventhough the generic arguments are different the end type is the same StatTest

Bounding

Example Class Hirachy.

private void TestExtends(T value){System.out.println(value.getClass()); }Only _2D and its childs Geometry geo=new Geometry(); _2D _2d=new _2D();

Square square=new Square();

TestExtends(_2d);

TestExtends(square);

//TestExtends(geo);Geometry is not a subclass of _2D

OutputUsageclass _2D

class Square  T extends ClassType, allows all classes that are subclasses and the class itself.

private void Test2D_OR_3D(T value){System.out.println(value.getClass());}Only childs of Geometry that implements _2DOR_3D interface Test2D_OR_3D(cube); Test2D_OR_3D(square);

OutputUsageclass Cube

class Square

 T extends ClassType & InterfaceType, allows all subclasses of ClassType and the ClassType itself that are Subclass or the class it self that of a class that implements InterfaceType. More interfaces can be specified seperated by &

private void TestCube(T value){System.out.println(value.getClass());}Only childs of classes that implements _2DOR_3D and DimensionSquare interfacesTestCube(cube);TestCube(square);

OutputUsage T extends InterfaceType & InterfaceType2, T is a class subclass of a class that implements InterfaceType1 and InterfaceType2class Cube

class Square

Generic arguments

TypeArguments: < ActualTypeArgumentList > ActualTypeArgumentList: ActualTypeArgument ActualTypeArgumentList , ActualTypeArgument ActualTypeArgument: ReferenceType Wildcard Wildcard: ? WildcardBoundsOpt WildcardBounds: extends ReferenceType super ReferenceType Generic Arguments Specification

public void DistinctGenericArgument(Holder value){ System.out.println(value.getValue().getClass()); }Distinct Type ArgumentDistinctGenericArgument(new Holder(geo));

OutputUsageclass Geometry

 The type of the given variable must be the exact same as the argument type.

public void WildChild(Holder value){ System.out.println(value.getValue().getClass()); }Childed wild card WildChild(new Holder(geo)); WildChild(new Holder(cube)); WildChild(new Holder(square));

OutputUsageclass Geometry

class Cube class Square  The generic type of the given variable must be a child of the generic argument type or it.

public void WildParent(Holder value){ System.out.println(value.getValue().getClass()); }Parent wild card WildParent(new Holder(geo)); WildParent(new Holder(new Object())); WildParent(new Holder<_2D>(_2d)); WildParent(new Holder(square));

OutputUsageclass Geometryclass java.lang.Objectclass _2Dclass Square  The generic type of the given variable must be a parent of the generic argument type or it.

public class GeoHolder extends Holder{public GeoHolder(T value){super(value);}} public void WildParentUpperBounded(GeoHolder value){ System.out.println(value.getValue().getClass()); } Upper bounded parent wild card WildParentUpperBounded(new GeoHolder(geo)); WildParentUpperBounded(new GeoHolder<_2D>(_2d)); WildParentUpperBounded(new GeoHolder(square));

OutputUsageclass Geometryclass _2Dclass Square

 To upper bound a wild card the generic parameter can define the upper bound

public class Write{private T name;public Write(T value){name=value;}public void setName(T a_name){name=a_name;}public T getName(){return name;}}public void WriteName(Write value){ value.setName("Test2"); System.out.println(value.getName());} Read only WildcardsWriteName(new Write("Ha"));

OutputUsage Can't write to values affected by the wildcard.Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method setName(capture#8-of ? extends String) in the type Main.Write is not applicable for the arguments (String)

at Main.WriteName(Main.java:35)at Main.main(Main.java:174) public class Holder {

}Generic arguments may not be primitive typesHolder h_int=new Holder(45);OutputUsage Primitive types are boolean, byte, short, int, long, char,float and double Use Boolean,Byte,Short,Integer,Long,Character,Float and Double as generic argument instead.Exception in thread "main" java.lang.Error: Unresolved compilation problems:

Syntax error on token "int", Dimensions expected after this token Syntax error on token "int", Dimensions expected after this token at Main.main(Main.java:90)

The Java Language Specification, Third Editionhttp://java.sun.com/docs/books/jls/third_edition/html/j3TOC.htmlGenerics in the Java Programming Languagehttp://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

quotesdbs_dbs8.pdfusesText_14