åæåã¨éçåæååã¨nativeã¡ã½ãã
ãåæåã®ååæå®æ°ã¯åæåã®ãã¼ãæã«ã¤ã³ã¹ã¿ã³ã¹åããããåæåã«ããã°ã©ãã追å ã§å®ç¾©ããéçåæååã®å
容ã¯ããã®åæå®æ°ã®ã¤ã³ã¹ã¿ã³ã¹åå¾ã«å®è¡ãããã追å ã®éçåæååãããåã«ã³ã³ãã¤ã©ãåæå®æ°ã®ã¤ã³ã¹ã¿ã³ã¹åãè¡ãéçåæååãæ¿å
¥ãã¦ãããããããªãã
ãä¾ãã°ã
public enum Foo { BAR, ZOT, QUX; static { System.out.println("static initialize"); } Foo() { System.out.println("construct " + name()); } }
ããããJVMã«ãã¼ãããã¨ã
$ java Foo construct BAR construct ZOT construct QUX static initialize Exception in thread "main" java.lang.NoSuchMethodError: main
ã®ããã«ãåæåã®ã³ã³ã¹ãã©ã¯ã¿ãå¼ãã§åæå®æ°ãã¤ã³ã¹ã¿ã³ã¹åããå¾ã§ã追å ã®éçåæååã®å
容ãå®è¡ããããæå¾ã®ã¨ã©ã¼ã¯mainã¡ã½ãããå®ç¾©ãã¦ããªãFooãjavaã³ãã³ãããå¼ãã ããã
ãéçåæååã®å
容ãã³ã³ã¹ãã©ã¯ã¿ãããå
ã«ã¯å®è¡ãããªãã¨ãããã®é åºã«ã¾ã¤ããè°è«ãJavaè¨èªä»æ§ã®åæåã®é
ç®ã«ããã¦ãªããã¦ãããããã§ã®ä¾ã¯ã宣è¨ã¨åæåãä¸ç·ã«è¡ã£ãã¯ã©ã¹å¤æ°ã«åæåã®ã³ã³ã¹ãã©ã¯ã¿ããã¢ã¯ã»ã¹ãããã¨ãã¦ãåæååã®ã¯ã©ã¹å¤æ°ãæ±ã£ã¦ãã¾ããã¨ã«ãªãã¨ãããã®ã解決çã¨ãã¦ãã³ã³ã¹ãã©ã¯ã¿ããã¯ã©ã¹å¤æ°ã¸ã®ã¢ã¯ã»ã¹ã追ãåºãã¦ãéçåæååã®ä¸ã§ã¯ã©ã¹å¤æ°ãæ±ãããã«å¤æ´ããæ¹æ³ã示ããã¦ããã
ãåæåã®ã³ã³ã¹ãã©ã¯ã¿ãããã®åå ã§å®ç¾©ãããnativeã¡ã½ãããå¼ã¶å ´åãåç´ã«éçåæååã§nativeã¡ã½ãããå®è£ ããã©ã¤ãã©ãªããã¼ãããããã«ã¯ãããªãã
public enum Foo { BAR, ZOT, QUX; static { System.loadLibrary("method-library"); } Foo() { method(); } private native void method(); }
ã¯ãã©ã¤ãã©ãªã®ãã¼ãããå
ã«nativeã¡ã½ãããå¼ã°ãããããå®è¡æã«java.lang.UnsatisfiedLinkErrorãæããããã
ã解決çã¨ãã¦ã¯ãnativeã¡ã½ããã®å®è¡ãã³ã³ã¹ãã©ã¯ã¿ã®å¤ã«åºããã¨ãã§ããã®ãªããåè¿°ã®Javaè¨èªä»æ§ã§ä¾ç¤ºããã¦ããæ¹æ³ãã¨ããã
public enum Foo { BAR, ZOT, QUX; static { System.loadLibrary("method-library"); for (Foo f : Foo.values()) f.method(); } private native void method(); }
ãã©ããã¦ãã³ã³ã¹ãã©ã¯ã¿å ã§å®è¡ããªããã°ãªããªãå ´åã¯ãåæåã®ã¤ã³ã¹ã¿ã³ã¹åã¯ã³ã³ãã¤ã©ãæ¿å ¥ããéçåæååã®ä¸ã§ã®ã¿è¡ããããã¨ãå©ç¨ãã¦ãéã«ã©ã¤ãã©ãªã®ãã¼ãã®æ¹ãåæåã®ã³ã³ã¹ãã©ã¯ã¿å ã§è¡ã£ã¦ãã¾ãã¨ããæã使ãããã³ã³ã¹ãã©ã¯ã¿ã¨ç¡é¢ä¿ã®nativeã¡ã½ãããåãã©ã¤ãã©ãªã«å®è£ ããã¦ããã¨ãã¦ããå¿ ãåæåã®ãã¼ãç´å¾ã«ã©ã¤ãã©ãªããã¼ããããã®ã§åé¡ãªãã¨æãããã
public enum Foo { BAR, ZOT, QUX; Foo() { System.loadLibrary("method-library"); method(); } private native void method(); }
ãSystem.loadLibraryã¡ã½ããã¯è¤æ°åå¼ã³åºãã¦ã2åç®ä»¥éã¯ç¡è¦ãããã®ã§ããã§ãåé¡ã¯ãªãæ°ããããæ°ã«ãªããããªãã
public enum Foo { BAR, ZOT, QUX; Foo() { if (ordinal() == 0) System.loadLibrary("method-library"); method(); } private native void method(); }
ã¨ããã°ãæåã«ã¤ã³ã¹ã¿ã³ã¹åãããï¼ã§ãããï¼*1åºæ°0ã®åæå®æ°ã®ã¤ã³ã¹ã¿ã³ã¹åã®éã ãã©ã¤ãã©ãªã®ãã¼ããè¡ããã¨ããã
*1:åºæ°0ããã¤ã³ã¹ã¿ã³ã¹åããããã¨ãè¨èªä»æ§ä¸å®ã¾ã£ã¦ããã®ã確èªããªãã¨ã¾ããã®ããã
å°çå°å¥³ ä¸é¼ #12 ãçå¤ã®ã°ã©ãã
ããã£ã±ãããæå³ã³ãã«ã«ãªããããåããªãã¨å°çå°å¥³ãããªãã§ãã誰ã誰ãã©ãããçç±ã§æµããã®èªããªãã§ã¯ä»åãä¸çªã ã£ãããã
ã¨ããéè¡ã®ç¦æ¸ç®é² #12 ã絶対è½åã
ãèãå½éº»ããã¼ã¬ã¼ãæ¦æ³ã§ç¸æã説å¾ã§ããã