type information - Using Class Literals

本文介绍了如何使用类字面量重实现PetCreator,这种方法在很多方面使代码更简洁。通过在OnJava8-Examples目录下运行PetCount2,并对比输出结果,可以展示类字面量的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

previous article

If we reimplement PetCreator using lcass literals, the result is cleaner in many ways:

// typeinfo/pets/LiteralPetCreator.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Using class literals
// {java typeinfo.pets.LiteralPetCreator}
package typeinfo.pets;

import java.util.*;

public class LiteralPetCreator extends PetCreator {
  // No try block needed.
  @SuppressWarnings("unchecked")
  public static final List<Class<? extends Pet>> ALL_TYPES =
      Collections.unmodifiableList(
          Arrays.asList(
              Pet.class,
              Dog.class,
              Cat.class,
              Rodent.class,
              Mutt.class,
              Pug.class,
              EgyptianMau.class,
              Manx.class,
              Cymric.class,
              Rat.class,
              Mouse.class,
              Hamster.class));
  // Types for random creation:
  private static final List<Class<? extends Pet>> TYPES =
      ALL_TYPES.subList(ALL_TYPES.indexOf(Cat.class), ALL_TYPES.size());

  @Override
  public List<Class<? extends Pet>> types() {
    return TYPES;
  }

  public static void main(String[] args) {
    System.out.println(TYPES);
  }
}
/* Output:
[class typeinfo.pets.Cat, class typeinfo.pets.Rodent, class typeinfo.pets.Mutt, class typeinfo.pets.Pug, class typeinfo.pets.EgyptianMau, class typeinfo.pets.Manx
, class typeinfo.pets.Cymric, class typeinfo.pets.Rat, class typeinfo.pets.Mouse, class typeinfo.pets.Hamster]
*/

run it by in OnJava8-Examples directory:

% javac typeinfo/pets/LiteralPetCreator.java
% java typeinfo.pets.LiteralPetCreator
/**
     * Returns an unmodifiable view of the specified list.  This method allows
     * modules to provide users with "read-only" access to internal
     * lists.  Query operations on the returned list "read through" to the
     * specified list, and attempts to modify the returned list, whether
     * direct or via its iterator, result in an
     * <tt>UnsupportedOperationException</tt>.<p>
     *
     * The returned list will be serializable if the specified list
     * is serializable. Similarly, the returned list will implement
     * {@link RandomAccess} if the specified list does.
     *
     * @param  <T> the class of the objects in the list
     * @param  list the list for which an unmodifiable view is to be returned.
     * @return an unmodifiable view of the specified list.
     */
    public static <T> List<T> unmodifiableList(List<? extends T> list) {
        return (list instanceof RandomAccess ?
                new UnmodifiableRandomAccessList<>(list) :
                new UnmodifiableList<>(list));
    }
// typeinfo/pets/Pets.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Facade to produce a default PetCreator
package typeinfo.pets;
import java.util.*;
import java.util.stream.*;

public class Pets {
  public static final PetCreator CREATOR =
    new LiteralPetCreator();
  public static Pet get() {
    return CREATOR.get();
  }
  public static Pet[] array(int size) {
    Pet[] result = new Pet[size];
    for(int i = 0; i < size; i++)
      result[i] = CREATOR.get();
    return result;
  }
  public static List<Pet> list(int size) {
    List<Pet> result = new ArrayList<>();
    Collections.addAll(result, array(size));
    return result;
  }
  public static Stream<Pet> stream() {
    return Stream.generate(CREATOR);
  }
}
// typeinfo/PetCount2.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import typeinfo.pets.*;

public class PetCount2 {
  public static void main(String[] args) {
    PetCount.countPets(Pets.CREATOR);
  }
}
/* Output:
Mouse Manx Pug Rodent Rodent Hamster Mouse Cat Mutt Rat Mouse Mouse Rodent Hamster Hamster Mouse Mouse Rodent Cat Mouse
{Pug=1, Mouse=7, Rat=1, Cat=3, Manx=1, Rodent=15, Mutt=1, Dog=2, Pet=20, Hamster=3}
*/

run PetCount2 please use 

./gradlew  :typeinfo:PetCount2

and use 

./gradlew  :typeinfo:PetCount

compare the output results.

next article

refrences:

1. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/typeinfo/pets/LiteralPetCreator.java

2. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Collections.java

3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/typeinfo/pets/PetCount.java

4. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/typeinfo/pets/PetCount2.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值