java枚举类型 变长参数 和反射机制的一些说明
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
枚举类型是JDK5.0的新特征。
Sun引进了一个全新的关键字enum来定义一个枚举类。
下面就是一个典型枚举类型的定义:
public enum Color{ RED,BLUE,BLACK,YELLOW,GREEN }
显然,enum很像特殊的class,实际上enum声明定义的类型就是一个类。
而这些类都是类库中Enum类的子类(ng.Enum<E>)。
它们继承了这个Enum中的许多有用的方法。
下面我们就详细介绍enum定义的枚举类的特征及其用法。
(后面均用Color举例)
1、Color枚举类是特殊的class,其枚举值(RED,BLUE...)是Color的类对象(类实例):
Color c=Color.RED;
而且这些枚举值都是public static final的,也就是我们经常所定义的常量方式,因此枚举类中的枚举值最好全部大写。
2、即然枚举类是class,当然在枚举类型中有构造器,方法和数据域。
但是,枚举类的构造器有很大的不同:(1) 构造器只是在构造枚举值的时候被调用。
enum Color{
RED(255,0,0),BLUE(0,0,255),BLACK(0,0,0),YELLOW(255,255,0),GREEN(0,255,0);
//构造枚举值,比如RED(255,0,0)
private Color(int rv,int gv,int bv){
this.redValue=rv;
this.greenValue=gv;
this.blueValue=bv;
}
public String toString(){ //自定义的public方法
return super.toString()+"("+redValue+","+greenValue+","+blueValue+")";
}
private int redValue; //自定义数据域,private为了封装。
private int greenValue;
private int blueValue;
}
(2) 构造器只能私有private,绝对不允许有public构造器。
这样可以保证外部代码无法新构造枚举类的实例。
这也是完全符合情理的,因为我们知道枚举值是public static final的常量而已。
但枚举类的方法和数据域可以允许外部访问。
public static void main(String args[])
{
// Color colors=new Color(100,200,300); //wrong
Color color=Color.RED;
System.out.println(color); // 调用了toString()方法
}
3、所有枚举类都继承了Enum的方法,下面我们详细介绍这些方法。
(1) ordinal()方法: 返回枚举值在枚举类种的顺序。
这个顺序根据枚举值声明的顺序而定。
Color.RED.ordinal(); //返回结果:0
Color.BLUE.ordinal(); //返回结果:1
(2) compareTo()方法: Enum实现了parable接口,因此可以比较象与指定对象的顺序。
Enum中的compareTo返回的是两个枚举值的顺序之差。
当然,前提是两个枚举值必须属于同一个枚举类,否则会抛出ClassCastException()异常。
(具体可见源代码)
pareTo(Color.BLUE); //返回结果-1
(3) values()方法:静态方法,返回一个包含全部枚举值的数组。
Color[] colors=Color.values();
for(Color c:colors){
System.out.print(c+","); }//返回结果:RED,BLUE,BLACK YELLOW,GREEN,
(4) toString()方法:返回枚举常量的名称。
Color c=Color.RED;
System.out.println(c);//返回结果: RED
(5) valueOf()方法:这个方法和toString方法是相对应的,返回带指定名称的指定枚举类型的枚举常量。
Color.valueOf("BLUE"); //返回结果: Color.BLUE
(6) equals()方法:比较两个枚举类对象的引用。
//JDK源代码:public final boolean equals(Object other) { return this==other;}
4、枚举类可以在switch语句中使用。
Color color=Color.RED;
switch(color){
case RED: System.out.println("it's red");break;
case BLUE: System.out.println("it's blue");break;
case BLACK: System.out.println("it's blue");break;
}
//-----------================---------------------------
public class m5 {
public static void main(String[] args) throws InstantiationException, IllegalAccessException { // TODO Auto-generated method stub
A x=new A();//new 的作用是建立实例对象,同时该句还调用了默认构造函数对实例对象初始化.
test.fs();
System.out.println(Color.R);
System.out.println(Color1.R);
System.out.println(Color1.R.f());
Color1 cd=Color1.B;
switch (Color1.R){
case B:
System.out.println("Color1之红");break;
case G:
System.out.println("Color1之绿");
//case Color1.G:System.out.println("Color1之绿"); //switch规定枚举举值前不能带类名Color1
//case cd System.out.println();//与C一样,不能用变量.只能是同一类型的常量.
//case D:System.out.println(); //D不是Color1枚举的常量
}
System.out.println(Food.Coffee.BLACK_COFFEE);
M5B.test();
}
}
class A{ A(){ //this(10); A(11); //构造函数是初始化的.的作用是建立实例对象. } A(int x){} int A(int x){ //不是构造函数 System.out.println("par x="+x); return x;} } class test{
static void fs() throws InstantiationException, IllegalAccessException
{
Class ic=int.class;
//Object obj1=ic.newInstance();//int 是基本数据类型,他没有构造函数,当然也没有默认构造函数.故错 //Object obj2=Integer.class.newInstance();//Integer 只有Integer(int value) 和Integer(String s)二种构造函数.没有默认构造.故错
}
}
//枚举常量的列表项之间用逗号,列表项的末尾可以有分号,也可以没有.但后有其它成员时必须有分号
enum Color{R,G,B,D;}
enum Color1{
R(255),G,B;
public int col1=255;
public int col2=0;
public int col3=0;
Color1(){col2=20;} //产邺private 默认就是非曲直private
private Color1(int x){col2=10;} //产邺private 默认就是非曲直private
int f(){return 10;}
}
interface Food {
enum Coffee implements Food{
BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO
}
enum Dessert implements Food{
FRUIT, CAKE, GELATO
}
}
//所有的枚举都继承自ng.Enum 类。
由于Java 不支持多继承,所以枚举对象不能再继承其他类。
结果:
par x=11
R
R
10
BLACK_COFFEE
15
15
15
115
115
115
interface Behaviour {
void print();
String getInfo();
}
enum Color2 implements Behaviour{
RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);
// 成员变量
private String name;
private int index;
// 构造方法
private Color2(String name, int index) {
= name;
this.index = index;
}
//接口方法
@Override
public String getInfo() {
return ;
}
//接口方法
@Override
public void print() {
System.out.println(this.index+":"+);
}
}
class M5B
{
static int f(int ...x)
{ int s=0;
for(int i:x)
s+=i;
return s;
}
/*不能重载,因为和上面的翻译名称一致.
static int f(int[] x)
{return 100;}
*/
//f重载函数
static int f(int x1,int x2) { return x1+x2;}
static int f1(int[]x) //int ...x与int[]x 意义不一样.看
{ int s=0;
for(int i:x)
s+=i;
return s;
}
static int f2(short t,int[]x)
{ int s=t;
for(int i:x)
s+=i;
return s;
}
static int f3(short t,int...x)
{ int s=t;
for(int i:x)
s+=i;
return s;
}
static void test()
{
System.out.println(f(1,2,3,4,5));
System.out.println(f(new int[]{1,2,3,4,5}));
//System.out.println(f1(1,2,3,4,5)); //The method f1(int[]) in the type M5B is not applicable for the arguments (int, int, int, int, int)
System.out.println(f1(new int[]{1,2,3,4,5}));
System.out.println(f2((short)100,new int[]{1,2,3,4,5}));
//System.out.println(f2((short)100,1,2,3,4,5));//The method f2(short, int[]) in the type M5B is not applicable for the arguments (short, int, int, int, int, int)
System.out.println(f3((short)100,new int[]{1,2,3,4,5}));
System.out.println(f3((short)100,1,2,3,4,5));
}
}
//--------------
import ng.reflect.*;
public class ReflectTester {
public Object copy(Object object) throws Exception{
//获得对象的类型
Class classType=object.getClass();
System.out.println("Class:"+classType.getName());
//通过默认构造方法创建一个新的对象
//public Constructor<T> getConstructor(Class<?>... parameterTypes)////public T newInstance(Object... initargs) Object objectCopy=classType.getConstructor().newInstance(); //对
//Object objectCopy=classType.getConstructor(new Class[]{}).newInstance(new Object[]{}); //对//获得对象的所有属性
Field fields[]=classType.getDeclaredFields();
for(int i=0; i<fields.length;i++){
Field field=fields[i];
String fieldName=field.getName();
String firstLetter=fieldName.substring(0,1).toUpperCase();
//获得和属性对应的getXXX()方法的名字
String getMethodName="get"+firstLetter+fieldName.substring(1);
//获得和属性对应的setXXX()方法的名字
String setMethodName="set"+firstLetter+fieldName.substring(1);
//获得和属性对应的getXXX()方法
Method getMethod=classType.getMethod(getMethodName,new Class[]{});
//获得和属性对应的setXXX()方法
Method setMethod=classType.getMethod(setMethodName,new Class[]{field.getType()});
//调用原对象的getXXX()方法
Object value=getMethod.invoke(object,new Object[]{});
System.out.println(fieldName+":"+value);
//调用拷贝对象的setXXX()方法
setMethod.invoke(objectCopy,new Object[]{value});
}
return objectCopy;
}
public static void main(String[] args) throws Exception{
Customer customer=new Customer("Tom",21);
customer.setId(new Long(1));
Customer customerCopy=(Customer)new ReflectTester().copy(customer);
System.out.println("Copy information:"+customerCopy.getName()+" "+customerCopy.getAge());
System.out.println("----------");
ReflectTesterMothd.formain(customer);
}
}
class ReflectTesterMothd {
public Object copy(Object object) throws Exception{
//获得对象的类型
Class classType=object.getClass();
System.out.println("object.getClass().getName() = "+classType.getName());
Object objectCopy=classType.getConstructor().newInstance(); //对
Method[] method=classType.getDeclaredMethods();
for(int i=0; i<method.length;i++){
Method md=method[i];
String methodName=md.getName();
if(methodName.substring(0, 3).equals("get"))
{
for(Method d:method)
{
String s=d.getName();
if(s.substring(0,3).equals("set") && s.substring(3).equals(methodName.substring(3)))
d.invoke(objectCopy, md.invoke(object));
}
}
}
return objectCopy;
}
public static void formain(Object ob) throws Exception{
Customer customerCopy=(Customer)new ReflectTesterMothd().copy(ob);
System.out.println(customerCopy.getId()+" "+customerCopy.getName()+" "+customerCopy.getAge());
}
}
class Customer{
private Long id;
private String name;
private int age;
public Customer(){}
public Customer(String name,int age){
=name;
this.age=age;
}
public Long getId(){return id;}
public void setId(Long id){this.id=id;}
public String getName(){return name;}
public void setName(String name){=name;}
public int getAge(){return age;}
public void setAge(int age){this.age=age;}
}
结果:
Class:Customer
id:1
name:Tom
age:21
Copy information:Tom 21
----------
object.getClass().getName() = Customer
1 Tom 21。