Class classes have been generalized, but many people begin to feel that their generics are confusing. What is the meaning of type parameter T in class<t>? It turns out that it is the referenced class interface. How could it be like this? Is that a circular inference? If not, why do you define it this way?
In the previous JDK, the definition of the Class.newinstance () method returns Object, and you most likely want to cast the return type to another type:
Class Class { Object newinstance (); } |
But with generics, you define the Class.newinstance () method with a more specific return type:
Class Class<t> { T newinstance (); } |
How do I create an instance of a class<t> type? Just like using non-generic code, there are two ways to call the method Class.forName () or use the class constant X.class. Class.forName () is defined to return class<?>. On the other hand, the class constant x.class is defined as having type class<x>, so String.class is the class<string> type.
What are the benefits of making Foo.class a class<foo> type? The big advantage is that with the magic of type inference, you can improve the type safety of code that uses reflection. In addition, it is not necessary to convert the Foo.class.newInstance () coercion type to Foo.
Consider a method that retrieves a set of objects from the database and returns a collection of JavaBeans objects. You instantiate and initialize the created object through reflection, but that does not mean that type safety must be completely thrown into the brain. Consider the following method:
Public static<t> list<t> GetRecords (class<t> C, Selector s) { Use Selector to select rows list<t> list = new arraylist<t> (); For (/* Iterate over results */) { T row = C.newinstance (); Use reflection to set fields from result List.add (row); } return list; } |
You can simply call the method as follows:
list<foorecord> L = getRecords (Foorecord.class, fooselector); |
compiler will be foorecord.class based on class< This fact of the foorecord> type infers the return type of GetRecords (). You use class constants to construct new instances and to provide the type information that the compiler uses in type checking.