Java specify class generic

Java-syntax for explicitly specifying generic arguments in method calls

How would this work for an import static method? It’s not attached to a class or this , and as you state the first syntax listed does not work.

@Coderer Well the static method must be in some class, so you can use SomeClass.genericMethod() . If you didn’t import the class, then you use the FQN of the class. I’m sure you know this and were hoping for a more satisfying answer. Personally I don’t see why the genericMethod() syntax couldn’t be added to the language; does it create an ambiguity?

I actually hadn’t tried the FQN of the class, I just switched from import static pack.MyClass.someMethod; someMethod(); to import pack.MyClass; MyClass.someMethod() , but of course it’s still more verbose than the «wish this worked» counterexample you give in the answer.

Yes. Sometimes type arguments are called type witnesses. That’s good to know, and I hadn’t known it before. The JLS uses the term type argument. The Generics trail of the Java tutorial sometimes use type argument and sometimes uses type witness.

According to the Java specification that would be for example:

Collections.unmodifiableSet() 

(Sorry for asking and answering my own question — I was just looking this up for the third time. 🙂

Читайте также:  Selenium java select all

A good example from java.util.Collection of specifying a generic method which defines its own generic type is Collection.toArray where the method signature looks like:

This declares a generic type T, which is defined on method call by the parameter T[] a and returns an array of T’s. So the same instance could call the toArray method in a generic fashion:

Collection collection = new ArrayList(); collection.add(1); collection.add(2); // Call generic method returning Integer[] Integer[] ints = collection.toArray(new Integer[]<>); // Call generic method again, this time returning an Number[] (Integer extends Number) Number[] nums = collection.toArray(new Number[]<>); 

Источник

Generic Types

A generic type is a generic class or interface that is parameterized over types. The following Box class will be modified to demonstrate the concept.

A Simple Box Class

Begin by examining a non-generic Box class that operates on objects of any type. It needs only to provide two methods: set, which adds an object to the box, and get, which retrieves it:

public class Box < private Object object; public void set(Object object) < this.object = object; >public Object get() < return object; >>

Since its methods accept or return an Object, you are free to pass in whatever you want, provided that it is not one of the primitive types. There is no way to verify, at compile time, how the class is used. One part of the code may place an Integer in the box and expect to get Integers out of it, while another part of the code may mistakenly pass in a String, resulting in a runtime error.

A Generic Version of the Box Class

A generic class is defined with the following format:

The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, . and Tn.

To update the Box class to use generics, you create a generic type declaration by changing the code «public class Box» to «public class Box ". This introduces the type variable, T, that can be used anywhere inside the class.

With this change, the Box class becomes:

/** * Generic version of the Box class. * @param the type of the value being boxed */ public class Box  < // T stands for "Type" private T t; public void set(T t) < this.t = t; >public T get() < return t; >>

As you can see, all occurrences of Object are replaced by T. A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.

This same technique can be applied to create generic interfaces.

Type Parameter Naming Conventions

By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.

The most commonly used type parameter names are:

  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types

You'll see these names used throughout the Java SE API and the rest of this lesson.

Invoking and Instantiating a Generic Type

To reference the generic Box class from within your code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer:

You can think of a generic type invocation as being similar to an ordinary method invocation, but instead of passing an argument to a method, you are passing a type argumentInteger in this case — to the Box class itself.

Type Parameter and Type Argument Terminology: Many developers use the terms "type parameter" and "type argument" interchangeably, but these terms are not the same. When coding, one provides type arguments in order to create a parameterized type. Therefore, the T in Foo is a type parameter and the String in Foo f is a type argument. This lesson observes this definition when using these terms.

Like any other variable declaration, this code does not actually create a new Box object. It simply declares that integerBox will hold a reference to a "Box of Integer", which is how Box is read.

An invocation of a generic type is generally known as a parameterized type.

To instantiate this class, use the new keyword, as usual, but place between the class name and the parenthesis:

The Diamond

In Java SE 7 and later, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond. For example, you can create an instance of Box with the following statement:

For more information on diamond notation and type inference, see Type Inference.

Multiple Type Parameters

As mentioned previously, a generic class can have multiple type parameters. For example, the generic OrderedPair class, which implements the generic Pair interface:

public interface Pair  < public K getKey(); public V getValue(); >public class OrderedPair implements Pair  < private K key; private V value; public OrderedPair(K key, V value) < this.key = key; this.value = value; >public K getKey() < return key; >public V getValue() < return value; >>

The following statements create two instantiations of the OrderedPair class:

Pair p1 = new OrderedPair("Even", 8); Pair p2 = new OrderedPair("hello", "world");

The code, new OrderedPair , instantiates K as a String and V as an Integer. Therefore, the parameter types of OrderedPair's constructor are String and Integer, respectively. Due to autoboxing, it is valid to pass a String and an int to the class.

As mentioned in The Diamond, because a Java compiler can infer the K and V types from the declaration OrderedPair , these statements can be shortened using diamond notation:

OrderedPair p1 = new OrderedPair<>("Even", 8); OrderedPair p2 = new OrderedPair<>("hello", "world");

To create a generic interface, follow the same conventions as for creating a generic class.

Parameterized Types

You can also substitute a type parameter (that is, K or V) with a parameterized type (that is, List ). For example, using the OrderedPair example:

OrderedPairBox > p = new OrderedPair<>("primes", new Box(. ));

Источник

Java Generics: How to specify a Class type for a generic typed class?

I have a POJO specified as: MyClass , where U is the generic type parameter. I am trying to write a utility method which accepts a class reference Class and populates a map of type Map (accepts the map to populate). This method is implemented like:

static void populateMap(Map map, Class type) < . // Parses into the specified type and returns an object of that type. T obj = parse(. type); map.put (key, obj); . return map; >

This compiles fine. In my caller, I attempt to populate a map with any MyClass instance (irrespective of type) as the value. Hence I use the following code:

// Loses type information Map> m = new HashMap<>(); populateMap(m, MyClass.class); 

@JunedAhsan No, I should be able to create a map containing any type of MyClass instances. This is why I have specified the wildcard.

@Lokesh Which class do you want to look at? The class containing populate Map is a simple util class. The method accepts the map as a composition.

2 Answers 2

In this case it should be safe to do an unchecked cast to Class> :

// This is okay because we're switching to a type with an unbounded wildcard - // the behaviors of Class.newInstance and Class.cast are still safe. @SuppressWarnings("unchecked") Class> classWithNarrowedType = (Class>)(Class)MyClass.class; populateMap(m, classWithNarrowedType); 

This is a crufty solution, especially if you have many call sites like this, but there's no getting around the fact that class literals are parameterized with raw types, making their use as factories of parameterized types like MyClass inherently awkward.

A potentially cleaner solution would decouple populateMap from the use of class literals:

interface Parser  < T parse(); >static void populateMap(Map map, Parser parser) < . >. Map> m = new HashMap<>(); Parser> myClassParser = new Parser>() < @Override public MyClassparse() < return parse(. MyClass.class); >>; populateMap(m, myClassParser); 

As an aside I recommend a more flexible signature (see What is PECS (Producer Extends Consumer Super)? for more info):

static void populateMap(Map map, Parser parser) 

Источник

set generic class type

In short, what you want is List.class ; the generic types are only available at compile-time, and are "erased" at run-time. There's a brief explanation here: http://docs.oracle.com/javase/tutorial/java/generics/erasure.html . and a bit more detail here: http://www.artima.com/weblogs/viewpost.jsp?thread=208860

Compiler has all information to check if type is correctly assigned or not. Why does it make me to use ugly suppress warnings annotations when I could (if it is supported by language of course) specify concrete type and not use raw generic Class. And then, ok, let type information be erased in runtime. But in source code why can not I have it specified?

In brief, the runtime type can't be checked, because the Class object (and the runtime environment that it reflects) doesn't have a slot for the generic type being filled-in, since in most (not all) cases, that can't be determined by the compiler for a Class-object… i.e. List.class would be .equal to List.class , they both yield Class = List.class … So even though in your example, asd would be of type Class> , you could likewise use asd to hold Class or something else. In the limited case where asd is final , you don't need asd …

You speak about runtime it is not important here. What important is to specify concrete type for generic class in source code. That is the main point of my question. You see, I need no runtime capabilities here.

Well, put another way: the reason that there are no specifications for generic types in the Class type or .class notation, is because it would not matter to the code it creates. Or, seen differently: Class expresses the methods and properties of any List, regardless of the specific type that it might be containing; and, as the signatures of those methods compile into types that take Object, you could (but should not) ignore the generic type specifications and e.g. push a String into a List (and wreak havoc)

Источник

Оцените статью