type information - Using Class Literals
程序员文章站
2022-03-27 08:05:21
previous articleIf 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.//...
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)); }
next article
refrences:
1. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/typeinfo/pets/LiteralPetCreator.java
本文地址:https://blog.csdn.net/wangbingfengf98/article/details/112000393
上一篇: 关于微信小程序slider的介绍
下一篇: java