简体   繁体   English

除了制作类型安全的集合之外,java中泛型的使用?

[英]Uses of generics in java other than making type safe collections?

我大多使用泛型来制作类型安全的集合。泛型的其他用途是什么?

I've used it to write a very slim DAO-layer: 我用它来编写一个非常纤薄的DAO层:

/*
  superclass for all entites, a requirement is that they have the 
  same kind of primary key
*/
public abstract class Entity {
}

/*
  superclass for all DAOs. contains all CRUD operations and anything else
  can be generalized
*/
public abstract class DAO<T extends Entity> {

  //assuming full control over the database, all entities have Integer pks.
  public T find(Integer pk) {...}
  public void save(T entity) {...}
  public void remove(T entity) {...}
  etc...

}

/*
  Complete example of an ideal DAO, assuming that there are no special
  operations specific for the Entity.
  Note the absence of any implementation at all.
*/
public class SpecificDAO extends DAO<SpecificEntity> {}

To allow user-created, custom classes to be used with your code. 允许用户创建的自定义类与代码一起使用。

Say you release an SDK that enables some kind of special functionality. 假设您发布了支持某种特殊功能的SDK。 Generics will allow developers to utilise your functionality in many places, with almost any class. 泛型将允许开发人员在许多地方使用您的功能,几乎任何类。

The purpose of generics to reduce code repetition. 泛型的目的是减少代码重复。

Another interesting use is to represent types as variables in Java's reflection framework . 另一个有趣的用途是在Java的反射框架中将类型表示为变量。

In particular, note that java.lang.Class has a type parameter, specifying which class the Class object represents. 特别要注意java.lang.Class有一个类型参数,指定Class对象所代表的Class

See Wikipedia for general information. 有关一般信息,请参阅Wikipedia

还有其他用途,例如泛型类和泛型方法。

Generic are used to make a generalised class, so when you create a class you can make it a parameterised class. Generic用于创建通用类,因此在创建类时,可以将其设置为参数化类。 Later on when its object is created, you can specify which datatype or classtype that class's parameters will get type-casted to. 稍后在创建其对象时,您可以指定类的参数将被类型转换为哪种数据类型或classtype。 Also, it can make a class cast safe, so that elements of only one datatype or classtype can be inserted. 此外,它可以使类转换安全,因此只能插入一种数据类型或classtype的元素。 This technique is mainly useful in data structure classes. 该技术主要用于数据结构类。

Generics enables types to be parameters Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. 泛型使类型成为参数泛型使类型(类和接口)在定义类,接口和方法时成为参数。 This is just like the familiar formal parameters used in method declarations. 这就像方法声明中使用的熟悉的形式参数一样。 The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types. 不同之处在于形式参数的输入是值,而类型参数输入是类型。 Example below:- Use of formal parameterized method and generics :- 示例如下: - 使用形式参数化方法和泛型: -

class Room {

    private Object object;

    public void add(Object object) {
        this.object = object;
    }

    public Object get() {
        return object;
    }
}

public class Main {
    public static void main(String[] args) {
        Room room = new Room();
        room.add(60);
        //room.add("60"); //this will cause a run-time error
        Integer i = (Integer)room.get();
        System.out.println(i);
    }
}

Generics version of above:- 上面的泛型版本: -

class Room<T> {

    private T t;

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

public class Main {
    public static void main(String[] args) {
        Room<Integer> room = new Room<Integer>();
        room.add(60);

        Integer i = room.get();
        System.out.println(i);
    }
}

In geneics version of class if someone adds room.add("60") , a compile-time error will be shown. 如果有人添加room.add("60") ,则在类的geneics版本中,将显示编译时错误。

1.Info source 2. Example taken from 1.Info source 2.取自的例子

Generics uses: 泛型使用:

  • Compile-time type safety. 编译时类型安全。
  • Avoid casting (hence avoid ClassCastException ). 避免强制转换(因此避免使用ClassCastException )。
  • Readable Code. 可读代码。

Refer Java Generics tutorial for detailed explanation. 有关详细说明,请参阅Java Generics教程

Enums are another example from the JDK. 枚举是JDK的另一个例子。 Basically whenever you have two classes working together, but don't know exactly which classes,generics become interesting. 基本上每当你有两个班级一起工作,但不确切知道哪些类,泛型变得有趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM