Want to improve this question? Add details and clarify the problem by editing this post.
Closed 11 years ago.
您可以只使用 Commons Enum 实现:
http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/enums/Enum.html
它允许您创建可以子类化的枚举。
You could just use the Commons Enum implementation instead:
which allows you to create Enum's that can then be subclassed.
这更简单,它能满足您的要求吗?
import java.util.*; interface Tree{ Tree parent(); Set<Tree> children(); } enum PrimaryColor implements Tree { Red,Green,Blue; @Override public Tree parent() { return null; } @Override public Set<Tree> children() { return Collections.unmodifiableSet(children); } final Set<Tree> children=new LinkedHashSet<Tree>(); } enum PastelColor implements Tree { Pink(PrimaryColor.Red),HotPink(PrimaryColor.Red),Rockmelon(PrimaryColor.Green),SkyBlue(PrimaryColor.Blue),BabyBlue(PrimaryColor.Blue); PastelColor(final PrimaryColor primaryColor) { this.primaryColor=primaryColor; if (primaryColor!=null) primaryColor.children.add(this); } @Override public Tree parent() { return primaryColor; } @Override public Set<Tree> children() { return Collections.emptySet(); } double percent() { return primaryColor.children().size()*100./EnumSet.allOf(super.getClass()).size(); } private final PrimaryColor primaryColor; } public class Main{ static double percent(final Tree tree) { final Tree parent=tree.parent(); if (tree instanceof Enum) { return parent.children().size()*100./((Enum)tree).getClass().getEnumConstants().length; } else throw new RuntimeException("strange tree!"); } public static void main(String[] args) { System.out.println("one way"); for(PastelColor pastelColor:PastelColor.values()) System.out.println(pastelColor+" "+pastelColor.percent()); System.out.println("another way"); for(PastelColor pastelColor:PastelColor.values()) System.out.println(pastelColor+" "+percent(pastelColor)); } }
this is simpler, does it do what you want?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
暂无简介
文章 0 评论 0
接受
发布评论
评论(2)
您可以只使用 Commons Enum 实现:
http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/enums/Enum.html
它允许您创建可以子类化的枚举。
You could just use the Commons Enum implementation instead:
http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/enums/Enum.html
which allows you to create Enum's that can then be subclassed.
这更简单,它能满足您的要求吗?
this is simpler, does it do what you want?