トップ «前の日記(2005-01-22) 最新 次の日記(2005-01-24)» 編集

日々の破片

著作一覧

2005-01-23

_ primitive型のClassインスタンス

どうもすぐに忘れてしまうな。

プリミティブのClassインスタンスは、プリミティブクラスのTYPEスタティックフィールドだ。

intなら、Integer.TYPE。

Foo#bar(int, boolean);のメソッドを引っ張るには、Foo.class.getMethod("bar", new Class[] { Integer.TYPE, Boolean.TYPE });と書けば良い。

import java.lang.reflect.*;
public class Foo {
    public void bar(int n, boolean b) {
        System.out.println("n=" + n + ", b=" + b);
    }
    public static void main(String[] args) throws Exception {
        Method m = Foo.class.getMethod("bar", new Class[] { Integer.TYPE, Boolean.TYPE });
        Foo f = new Foo();
        m.invoke(f, new Object[] { new Integer(801), Boolean.FALSE });
    }
}
=>
$ java Foo
n=801, b=false

ちなみにC#だと何でもtypeofで取れるから覚えることはない。

using System;
using System.Reflection;
public class Foo {
    public void bar(int n, bool b) {
        System.Console.WriteLine("n=" + n + ", b=" + b);
    }
    public static void Main() {
        MethodInfo m = typeof(Foo).GetMethod("bar", new Type[] { typeof(int), typeof(bool) });
        Foo f = new Foo();
        m.Invoke(f, new Object[] { 801, false });
    }
}

なんて書いてからふと気付いてやってみると

import java.lang.reflect.*;
 
public class Foo {
    public void bar(int n, boolean b) {
        System.out.println("n=" + n + ", b=" + b);
    }
    public static void main(String[] args) throws Exception {
        Method m = Foo.class.getMethod("bar", new Class[] { int.class, boolean.class });
        Foo f = new Foo();
        m.invoke(f, new Object[] { new Integer(801), Boolean.FALSE });
    }
}

なんのことはなく、int.classとか書けるんじゃん。知らなかったよ。

良く見たらClass Literalsに記述があるな。


2003|06|07|08|09|10|11|12|
2004|01|02|03|04|05|06|07|08|09|10|11|12|
2005|01|02|03|04|05|06|07|08|09|10|11|12|
2006|01|02|03|04|05|06|07|08|09|10|11|12|
2007|01|02|03|04|05|06|07|08|09|10|11|12|
2008|01|02|03|04|05|06|07|08|09|10|11|12|
2009|01|02|03|04|05|06|07|08|09|10|11|12|
2010|01|02|03|04|05|06|07|08|09|10|11|12|
2011|01|02|03|04|05|06|07|08|09|10|11|12|
2012|01|02|03|04|05|06|07|08|09|10|11|12|
2013|01|02|03|04|05|06|07|08|09|10|11|12|
2014|01|02|03|04|05|06|07|08|09|10|11|12|
2015|01|02|03|04|05|06|07|08|09|10|11|12|
2016|01|02|03|04|05|06|07|08|09|10|11|12|
2017|01|02|03|04|05|06|07|08|09|10|11|12|
2018|01|02|03|04|05|06|07|08|09|10|11|12|
2019|01|02|03|04|05|06|07|08|09|10|11|12|
2020|01|02|03|04|05|06|07|08|09|10|11|12|
2021|01|02|03|04|05|06|07|08|09|10|11|12|
2022|01|02|03|04|05|06|07|08|09|10|11|12|
2023|01|02|03|04|05|06|07|08|09|10|11|12|
2024|01|02|03|

ジェズイットを見習え