Reflection Example

다음은  Command 라인에서 입력된 클래스의 메소드를 실행(Invoke)하는 예제이다.

 

package reflect;

 

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

 

class Invoke {

       public static void main(String[] args) {

              try {

                     Class c = Class.forName(args[0]);

                     Method m = c.getMethod(args[1]);

                     Object ret = m.invoke(null);

                     System.out.println("Invoked static method: " + args[1] + " of class: " + args[0]

                                  + " with no args\nResults: " + ret);

 

              } catch (ClassNotFoundException e) {

                     System.out.println(e);

              } catch (NoSuchMethodException e2) {

                     System.out.println(e2);

              } catch (IllegalAccessException e3) {

                     System.out.println(e3);

              } catch (InvocationTargetException e) {

                     System.out.println(e);

                     System.out.println("Method threw an: " + e.getTargetException());

              }

       }

} 

 

% java   java.lang.System   currentTimeMillis

 

결과 : 

Invoked static method: currentTimeMillis of class: java.lang.System with no args

Results: 1360164595776

 

 

'Java > The Java Language' 카테고리의 다른 글

Text Encoding  (0) 2013.10.12
Java Dynamic Proxy --> Draft  (0) 2013.02.07
What is Enum in Java  (1) 2013.02.06
Static and Nostatic Initializer blocks  (0) 2013.02.06
Assertion  (1) 2013.02.06
Posted by Steven J.S Min
,

Interface as Callback

호출자(Caller) 피호출자(Callee) 호출하는 것이 아니라 피호출자(Callee) 호출자(Caller) 호출하는 것을 말한다

 

callback 포인터나 핸들러를 넘겨줘서 피호출자(Callee) 호출자(Caller) 호출하는 기법으로 코드 재상용이 가능하고, 비동기적으로 처리할 있으며 함수를 추상화 있기 때문에 UI 비동기 처리 시스템에서 callback 기법을 많이 사용한다.

 

java에서는 Callback메커니즘을 구현하기 위해 Interface 사용한다. Java Interface 이용하여 높은 수준의 층에 정의된 서브루틴(또는 함수) 낮은 수준의 추상화층이 호출할 있도록 구성할 있다. 어떤 함수의 정확한 동작은 낮은 수준의 함수에 넘겨주는 함수 포인터(핸들러) 의해 바뀐다. 이것은 코드 재사용을 하는 매우 강력한 기법이라고 말할 있다.

 

다음예제는TextReceiver 콜백으로 사용할 메소드를 등록하여 Interface 구성하고TickerTape 콜백함수를 구현한다. TextSource에서는 생성자에TextReceiver 레퍼런스를 갖도록 한다.

 

TextReceiver.java

 

package callback;

 

/**

 * Callback 메소드 등록

 *

 * @author Steven J.S Min

 *

 */

public interface TextReceiver {

       public void receiveText(String text);

}

 

TickerTape.java

 

package callback;

 

/**

 * 이것은 Output기기중 하나입니다.

 *

 * @author Steven J.S Min

 *

 */

public class TickerTape implements TextReceiver {

 

       @Override

       public void receiveText(String text) {

              System.out.println("TICKER: " + text);

       }

 

}

 

TextSource.java

 

package callback;

 

/**

 * 이클래스에서 주의해서 봐야할 점은 TextSource 오로지 Output 기기로 주어진 메시지를 출력하는 메소드에만 관심을 갖는 다는

 * 것이다. 어떤 함수의 정확한 동작은 낮은 수준의 함수에 넘겨주는 함수 포인터(핸들러) 의해 바뀐다.

 * 이것은 코드 재사용을 하는 매우 강력한 기법이라고 말할 있다.

 *

 * @author Steven J.S Min

 *

 */

public class TextSource {

       TextReceiver receiver; // Reference to the implemented Interface

 

       TextSource(TextReceiver r) {

              receiver = r;

       }

 

       public void sendText(String s) {

              receiver.receiveText(s);

       }

 

       /**

        * @param args

        */

       public static void main(String[] args) {

 

              // Create a object of the class that implements the interface

              TextReceiver tickerTape = new TickerTape();

 

              // Create a object of the class holding the reference to a interface implementation

              TextSource myCar = new TextSource(tickerTape);

 

              // Send a text message, which is our event.

              myCar.sendText("Hallo");

       }

 

}

 

결과 :

    TICKER: Hallo

 

추가 참조 : Observers and Observables [ http://stevenjsmin.tistory.com/36 ]

Posted by Steven J.S Min
,

Enumeration 다음과 같은 특징을 갖는다.


§  자바의 Object Type이다.

§  제한된 (a limited to an explicit set) 갖는다.

§  값의 순서를 갖는다.(선언된 순서로)

§  문자열의 이름을 갖는다.(선언된 이름)

 

 

public class EnumTest {

 

       enum Weekday {

              Sunday, Monday, Tuesday, Wednsday, Friday, Saturday

       }

 

       /**

        * @param args

        */

       public static void main(String[] args) {

              for (Weekday day : Weekday.values()) {

                     System.out.println(day.name());

              }

       }

}

 


Java compilerEnumTest.class 함께Weekday.class 함께 자동으로 생성한다. 따라서 javap 생성된 클래스를 확인해보면 Weekday Enumeration 타입이 어떤 형태로 어떻게 생성되었는지 확인할수 있다. 

 

C:\Temp>javap Weekday

Compiled from "Weekday.java"

public class Weekday extends java.lang.Enum<Weekday> {

  public static final Weekday Sunday;

  public static final Weekday Monday;

  public static final Weekday Tuesday;

  public static final Weekday Wednesday;

  public static final Weekday Thursday;

  public static final Weekday Friday;

  public static final Weekday Saturday;

  int fun;

  static {};

  public int getFun();

  public static Weekday[] values();

  public static Weekday valueOf(java.lang.String);

  Weekday(java.lang.String, int, int, Weekday);

} 


따라서 Weekday 타입을(하나의 클래스를 이용하듯) 항목들을 이용하면 된다.

 

Enum Values

 

 

Weekday [] weekdays = Weekday.values();



또는


 

for (Weekday day : Weekday.values()) {

       System.out.println(day.name());

}



 

Customizing Enumerations

Enumeration 형도 클래스변수, 생성자 그리고 기타 메소드 들을 추가 할수있다.

 

 

public class EnumTest {

 

       enum Weekday {

              Sunday(8), Monday(0), Tuesday(1), Wednsday(2), Thursday(4), Friday(6), Saturday(10);

 

              int fun;

 

              Weekday(int fun) {

                     this.fun = fun;

              }

 

              public int getFun() {

                     return fun;

              }

       };

 

       /**

        * @param args

        */

       public static void main(String[] args) {

              for (Weekday day : Weekday.values()) {

                     System.out.println(day.getFun());

              }

       }

}



   

또는 다음과 같은 하나의 Item Subclass 생성하듯 코딩할수 있다.

 


 enum Cat {

        HimilyanSiameseCaleco,

        Persian {

               public void someMethod() { ... }

        }

 }


     

위의 예제와 같은 경우 Persian.class 파일이 생성되고 Cat.Persian 같은 형태로 접근이 가능하다.




Enum in Java
is a keyword, a feature which is used to represent fixed number of well known values in Java, For example Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import. Java Enum as type is more suitable on certain cases for example representing state of Order as NEW, PARTIAL FILL, FILL or CLOSED. Enumeration(Enum) was not originally available in Java though it was available in other language like C and C++ but eventually Java realized and introduced Enum on JDK 5 (Tiger) by keyword Enum. In this Java Enum tutorial we will see different Enum example in Java and learn using Enum in Java. Focus of this Java Enum tutorial will be on different features provided by Enum in Java and how to use them. If you have used Enumeration before in C or C++ than you will not be uncomfortable with Java Enum but in my opinion Enum in Java is more rich and versatile than in any other language. One of the common use of Enum which emerges is Using Enum to write Singleton in Java, which is by far easiest way to implement Singleton and handles several issues related to thread-safety, Serialization automatically.

 


How to represent enumerable value without Java enum

Since Enum in Java is only available from Java 1.5 its worth to discuss how we used to represent enumerable values in Java prior JDK 1.5 and without it. I use public static final constant to replicate enum like behavior. Let’s see an Enum example in Java to understand the concept better. In this example we will use US Currency Coin as enumerable which has values like PENNY (1) NICKLE (5), DIME (10), and QUARTER (25).

class CurrencyDenom {
            public static final int PENNY = 1;
            public static final int NICKLE = 5;
            public static final int DIME = 10;
            public static final int QUARTER = 25;

      }

class Currency {
   int currency; //CurrencyDenom.PENNY,CurrencyDenom.NICKLE,
                 // CurrencyDenom.DIME,CurrencyDenom.QUARTER
}

 Though this can server our purpose it has some serious limitations:

 1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to currency e.g. 99 though there is no coin to represent that value.

 2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"

3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5

Java Enum is answer of all this limitation. Enum in Java is type-safe, provides meaningful String names and has there own namespace. Now let's see same example using Enum in Java:

public enum Currency {PENNY, NICKLE, DIME, QUARTER};
 
Here Currency is our enum and PENNY, NICKLE, DIME, QUARTER are enum constants. Notice curly braces around enum constants because Enum are type like class and interface in Java. Also we have followed similar naming convention for enum like class and interface (first letter in Caps) and since Enum constants are implicitly static final we have used all caps to specify them like Constants in Java.

What is Enum in Java

Now back to primary questions “What is Enum in java” simple answer Enum is a keyword in java and on more detail term Java Enum is type like class and interface and can be used to define a set of Enum constants. Enum constants are implicitly static and final and you can not change there value once created. Enum in Java provides type-safety and can be used inside switch statment like int variables. Since enum is a keyword you can not use as variable name and since its only introduced in JDK 1.5 all your previous code which has enum as variable name will not work and needs to be re-factored.

Benefits of Enums in Java:

1) Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. It is compiler error to assign something else unlike the public static final variables used in Enum int pattern and Enum String pattern.

2) Enum has its own name-space.

3) Best feature of Enum is you can use Enum in Java inside Switch statement like int or char primitive data type.we will also see example of using java enum in switch statement in this java enum tutorial.

4) Adding new constants on Enum in Java is easy and you can add new constants without breaking existing code.


Important points about Enum in Java

1) Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example "Currency" in below example and you can not assign any value other than specified in Enum Constants.
 
public enum Currency {PENNY, NICKLE, DIME, QUARTER};
Currency coin = Currency.PENNY;
coin = 1; //compilation error  


2) Enum in Java are reference type like class or interface and you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++ as shown in next example of Java Enum type.


3) You can specify values of enum constants at the creation time as shown in below example:
public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)};
But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.
  
public enum Currency {
        PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
        private int value;

        private Currency(int value) {
                this.value = value;
        }
};  
Constructor of enum in java must be private any other access modifier will result in compilation error. Now to get the value associated with each coin you can define a public getValue() method inside java enum like any normal java class. Also semi colon in the first line is optional.


4) Enum constants are implicitly static and final and can not be changed once created. For example below code of java enum will result in compilation error:

Currency.PENNY = Currency.DIME;
The final field EnumExamples.Currency.PENNY cannot be re assigned.

 
 
5) Enum in java can be used as an argument on switch statment and with "case:" like int or char primitive type. This feature of java enum makes them very useful for switch operations. Let’s see an example of how to use java enum inside switch statement:  

   Currency usCoin = Currency.DIME;
    switch (usCoin) {
            case PENNY:
                    System.out.println("Penny coin");
                    break;
            case NICKLE:
                    System.out.println("Nickle coin");
                    break;
            case DIME:
                    System.out.println("Dime coin");
                    break;
            case QUARTER:
                    System.out.println("Quarter coin");
    }
  
from JDK 7 onwards you can also String in Switch case in Java code.

6) Since constants defined inside Enum in Java are final you can safely compare them using "==" equality operator as shown in following example of  Java Enum:

Currency usCoin = Currency.DIME;
if(usCoin == Currency.DIME){
  System.out.println("enum in java can be compared using ==");
}

By the way comparing objects using == operator is not recommended, Always use equals() method or compareTo() method to compare Objects.

7) Java compiler automatically generates static values() method for every enum in java. Values() method returns array of Enum constants in the same order they have listed in Enum and you can use values() to iterate over values of Enum  in Java as shown in below example:

for(Currency coin: Currency.values()){
        System.out.println("coin: " + coin);
}

And it will print:
coin: PENNY
coin: NICKLE
coin: DIME
coin: QUARTER
               
Notice the order its exactly same with defined order in enums.


 
8) In Java Enum can override methods also. Let’s see an example of overriding toString() method inside Enum in Java to provide meaningful description for enums constants.

public enum Currency {
  ........
      
  @Override
  public String toString() {
       switch (this) {
         case PENNY:
              System.out.println("Penny: " + value);
              break;
         case NICKLE:
              System.out.println("Nickle: " + value);
              break;
         case DIME:
              System.out.println("Dime: " + value);
              break;
         case QUARTER:
              System.out.println("Quarter: " + value);
        }
  return super.toString();
 }
};        
And here is how it looks like when displayed:
Currency usCoin = Currency.DIME;
System.out.println(usCoin);

output:
Dime: 10


     
9) Two new collection classes EnumMap and EnumSet are added into collection package to support Java Enum. These classes are high performance implementation of Map and Set interface in Java and we should use this whenever there is any opportunity.



10) You can not create instance of enums by using new operator in Java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.


11) Instance of Enum in Java is created when any Enum constants are first called or referenced in code.


12) Enum in Java can implement the interface and override any method like normal class It’s also worth noting that Enum in java implicitly implement both Serializable and Comparable interface. Let's see and example of how to implement interface using Java Enum:

public enum Currency implements Runnable{
  PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
  private int value;
  ............
        
  @Override
  public void run() {
  System.out.println("Enum in Java implement interfaces");
                
   }
}



13) You can define abstract methods inside Enum in Java and can also provide different implementation for different instances of enum in java.  Let’s see an example of using abstract method inside enum in java

public enum Currency implements Runnable{
          PENNY(1) {
                  @Override
                  public String color() {
                          return "copper";
                  }
          }, NICKLE(5) {
                  @Override
                  public String color() {
                          return "bronze";
                  }
          }, DIME(10) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          }, QUARTER(25) {
                  @Override
                  public String color() {
                          return "silver";
                  }
          };
          private int value;

          public abstract String color();
        
          private Currency(int value) {
                  this.value = value;
          }
          ..............
  }      
In this example since every coin will have different color we made the color() method abstract and let each instance of Enum to define   there own color. You can get color of any coin by just calling color() method as shown in below example of java enum:

System.out.println("Color: " + Currency.DIME.color());


 
Enum Java valueOf example
One of my reader pointed out that I have not mention about valueOf method of enum in Java, which is used to convert String to enum in java.  Here is what he has suggested, thanks @ Anonymous
“You could also include valueOf() method of enum in java which is added by compiler in any enum along with values() method. Enum valueOf() is a static method which takes a string argument and can be used to convert a String into enum. One think though you would like to keep in mind is that valueOf(String) method of enum will throw "Exception in thread "main" java.lang.IllegalArgumentException: No enum const class" if you supply any string other than enum values.

Another of my reader suggested about ordenal() and name() utility method of java enum Ordinal method of Java Enum returns position of a Enum constant as they declared in enum while name()of Enum returns the exact string which is used to create that particular Enum constant.” name() method can also be used for converting Enum to String in Java.

Read more: http://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html#ixzz2K6atNL00

 

Enmeration 예제

                                

Weekdays.java

  package test;

 

  public enum Weekdays {

        Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

   }

 

 

                                                                                                                                                                                                    

EnumTest.java

  package test;

 

  public EnumTest {

 

       /**

        * @param args

        */

       public static void main(String[] args) {

              Weekdays weekday = Weekdays.valueOf("Monday");

              System.out.println(weekday);

             

              System.out.println("--------------");

 

              Weekdays days[] = Weekdays.values();

              for (int i = 0; i < days.length; i++) {

                     System.out.println(days[i]);

              }

 

              System.out.println("--------------");

              System.out.println(Weekdays.Sunday);

             

       }

  }

 

 

 

 결과 :

 

Monday

--------------

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

Sunday

--------------

Sunday


'Java > The Java Language' 카테고리의 다른 글

Java Dynamic Proxy --> Draft  (0) 2013.02.07
The Class Class and Reflection  (0) 2013.02.07
Static and Nostatic Initializer blocks  (0) 2013.02.06
Assertion  (1) 2013.02.06
Java stack trace with line numbers  (0) 2013.02.06
Posted by Steven J.S Min
,

이 코드블럭은 특정 메소드에 속해진 것이 아니지만 이블럭은 Constructor가 실행될때 단 한번 수행되어지거나

코드블럭에 static이라고 선언된 경우 클래스가 로딩될때 한번 수행되어진다.

따라서 static 변수를 초기화 하거나 실행 프로그램의 초기화 용도록 사용하면 요긴하겠다.

 

일반 코드블럭의 예

package test;

 

import java.util.Properties;

 

public class MyClass {

 

       Properties myProps = new Properties();

       // set up myProps

       {

              myProps.put("food", "bar");

              myProps.put("boo", "gee");

       }

       int a = 5;

       // TODO....

}

 

Static 코드블럭의 예

package test;

 

import java.awt.Color;

import java.util.Hashtable;

 

public class ColorWheel {

 

       static Hashtable colors = new Hashtable();

 

       // set up colors

       static {

              colors.put("Red", Color.red);

              colors.put("Greed", Color.green);

              colors.put("Blue", Color.blue);

              // TODO....

       }

 

}

 

'Java > The Java Language' 카테고리의 다른 글

The Class Class and Reflection  (0) 2013.02.07
What is Enum in Java  (1) 2013.02.06
Assertion  (1) 2013.02.06
Java stack trace with line numbers  (0) 2013.02.06
JVM Architecture  (0) 2013.02.06
Posted by Steven J.S Min
,