2012-01-14 8 views
7

任意の型からJavaのプリミティブ型への型キャストを定義したいと思います。任意のタイプから他の任意のタイプへのキャストを定義することは可能ですか?Javaでの型キャストの定義

public class Foo{ 
    //methods, constructor etc for this class 
    ... 
    //make it possible to cast an object of type Foo to an integer 
} 
//example of how an object of type foo would be cast to an integer 
public class Bar(){ 
    public static void main(String[] args){ 
     Foo foo1 = new Foo(); 
     int int1 = (int)foo1; 
     System.out.println(int1+""); 
    } 
} 
+0

これは可能ではありませんが、おそらく誰かがこれを修正することができます。 – AHungerArtist

+0

クラスに同じ変数がある限り、キャストのような構造体が存在することはありますか? –

+0

@LeeScottいいえ、Javaは 'ClassCastException'をスローします – Dave

答えて

9

あなたはそれをキャストすることはできませんが、変換機能を提供することができます。

public class Foo{ 
    //methods, constructor etc for this class 
    ... 
    public int toInt(){ 
     //convert to an int. 
    }  
} 

バーは、次のようになります。

public class Bar(){ 
    public static void main(String[] args){ 
     Foo foo1 = new Foo(); 
     int int1 = foo1.toInt(); 
     System.out.println(int1+""); 
    } 
} 
1

Fooクラス数を拡張する必要があります。なぜあなたはそれをしたいのですか?なぜfooのint変数にアクセスするだけではないのですか?

3

クラス型(Fooなど)からプリミティブ型に直接変換することはできません。代わりに、Fooオブジェクトの値を整数として返すメソッド(たとえば、int asInteger())を定義する必要があります。

3

いいえ、そうではありません。実際には意味がありません。Fooはどうすればintになりますか?

むしろのような適切な方法、一連の定義:例えばintInteger間などプリミティブ型とJava型との間

public int toInt() { return 42; } 

型キャストは、あっても本来のJavaの一部ではなかったです。