package cn.vicky; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class MySet { private Set<String> set = new HashSet<String>(); public Set<String> getSet(){ return set; } public Set<String> getUnSet(){ return Collections.unmodifiableSet(set); // 返回的Set无法添加数据。 } public static void main(String[] args) { MySet m = new MySet(); m.getSet().add("1"); m.getSet().add("2"); m.getSet().add("3"); // 将会出错 // m.getUnSet().add("4"); // throw java.lang.UnsupportedOperationException. // 判断类,或接口,是否是指定类的父类,或接口 System.out.println(m.getClass().isAssignableFrom(Object.class)); System.out.println(m.getClass().isAssignableFrom(MySetChild.class)); // 将一个类Object对象,转换为其真实类的父类 Object obj = new MySetChild(); MySet m2 = MySet.class.cast(obj); System.out.println(m2); // 获得类的子类 Class clazz = m2.getClass().asSubclass(MySetChild.class); System.out.println(clazz); } } falsetruecn.vicky.MySetChild@c17164class cn.vicky.MySetChild 使用: public class ComponentRegistry { ComponentRegistry() { componentSet = new LinkedHashSet(); } public Object getComponent(Class type) { Object matchingComponent = null; Iterator i$ = componentSet.iterator(); do { if(!i$.hasNext()) break; Object component = i$.next(); if(type.isAssignableFrom(component.getClass())) { if(matchingComponent != null) throw new MissingResourceException("More than one matching component", type.getName(), null); matchingComponent = component; } } while(true); if(matchingComponent == null) throw new MissingResourceException("No matching components", type.getName(), null); else return type.cast(matchingComponent); } void addComponent(Object component) { componentSet.add(component); } public Iterator iterator() { return Collections.unmodifiableSet(componentSet).iterator(); } private LinkedHashSet componentSet; }