- import java.lang.reflect.Constructor;
- public class Demo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //WeekDay
- Class clazz = WeekDay.MON.getClass();//@0 用getClass()获得的构造函数是一个
- //?1: 为何是一个? 为何会少掉构造函数?少掉了哪些构造函数?
- Constructor[] cons = clazz.getDeclaredConstructors();
- System.out.println("共有 "+cons.length+" 个构造函数");
- for (Constructor con : cons) {
- System.out.println(con.toGenericString());
- }
- Class clazz1 = WeekDay.class;//@1 与@0 相比 用 .class 的方法却获得3个。
- //?2: 为何是3个 ,多出来的那个构造函数是什么意思? ?3: 为何与@0 不同?
- Constructor[] cons1 = clazz1.getDeclaredConstructors();
- System.out.println("共有 "+cons1.length+" 个构造函数");
- for (Constructor con : cons1) {
- System.out.println(con.toGenericString());
- }
- System.out.println();
- //Weekday1
- Class clazz2 = Weekday1.MON.getClass();//@2 与@0 相比 该方法enum 没有 abstract 方法, 获得的构造函数却是2个
- Constructor[] cons2 = clazz2.getDeclaredConstructors();
- System.out.println("共有 "+cons2.length+" 个构造函数");
- for (Constructor con : cons2) {
- System.out.println(con.toGenericString());
- }
- Class clazz3 = Weekday1.class;//@3 比较WeekDay 和 Weekday1,WeekDay仅多了一个abstract方法。
- //说明WeekDay 之所以会多出或少掉构造函数是因为 abstract 方法
- //?4:为何WeekDay 和 Weekday1 会有这样的差异?或者为何abstract方法会造成这样的差异
- Constructor[] cons3 = clazz3.getDeclaredConstructors();
- System.out.println("共有 "+cons3.length+" 个构造函数");
- for (Constructor con : cons3) {
- System.out.println(con.toGenericString());
- }
- }
- }
- enum WeekDay{
- SUN(){
- public WeekDay nextDay(){
- return MON;
- }
- },MON(){
- public WeekDay nextDay(){
- return SUN;
- }
- };
- WeekDay(){
- System.out.println("first");
- }
- WeekDay(int x){
- System.out.println("second");
- }
- public abstract WeekDay nextDay();
- }
- enum Weekday1{
- SUN,MON;
- Weekday1(){
- System.out.println("first");
- }
- Weekday1(int x){
- System.out.println("second");
- }
- }
- /*输出结果为:
- first
- first
- 共有 1 个构造函数
- test.WeekDay$$$$2(java.lang.String,int)
- 共有 3 个构造函数
- private test.WeekDay(java.lang.String,int,int)
- private test.WeekDay(java.lang.String,int)
- test.WeekDay(java.lang.String,int,test.WeekDay)
- first
- first
- 共有 2 个构造函数
- private test.Weekday1(java.lang.String,int,int)
- private test.Weekday1(java.lang.String,int)
- 共有 2 个构造函数
- private test.Weekday1(java.lang.String,int,int)
- private test.Weekday1(java.lang.String,int)
- */
复制代码 问题就是 ?1:?2:?3:?4
|