87

I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds?

FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.


I don't know of anything that's built to handle this specific case, but you could use Mono.Cecil. Reflect the assemblies and then count references in the IL. Shouldn't be too tough.

4

12 に答える 12

101

In C#:
Fixed with recommendation from Mike

ArrayList list = ...;
// List<object> list = ...;
foreach (object o in list) {
    if (o is int) {
        HandleInt((int)o);
    }
    else if (o is string) {
        HandleString((string)o);
    }
    ...
}

In Java:

ArrayList<Object> list = ...;
for (Object o : list) {
    if (o instanceof Integer)) {
        handleInt((Integer o).intValue());
    }
    else if (o instanceof String)) {
        handleString((String)o);
    }
    ...
}
于 2008-09-19T23:20:42.850 に答える
54

You can use the getClass() method, or you can use instanceof. For example

for (Object obj : list) {
  if (obj instanceof String) {
   ...
  }
}

or

for (Object obj : list) {
 if (obj.getClass().equals(String.class)) {
   ...
 }
}

Note that instanceof will match subclasses. For instance, of C is a subclass of A, then the following will be true:

C c = new C();
assert c instanceof A;

However, the following will be false:

C c = new C();
assert !c.getClass().equals(A.class)
于 2008-09-19T23:28:41.300 に答える
45
for (Object object : list) {
    System.out.println(object.getClass().getName());
}
于 2008-09-19T23:23:24.480 に答える
13

次のようなものを使用することはほとんどありません。

Object o = ...
if (o.getClass().equals(Foo.class)) {
    ...
}

可能なサブクラスを考慮していないためです。あなたは本当に Class#isAssignableFrom を使いたい:

Object o = ...
if (Foo.class.isAssignableFrom(o)) {
    ...
}
于 2008-09-21T00:04:18.213 に答える
5

Java では、instanceof 演算子を使用するだけです。これにより、サブクラスも処理されます。

ArrayList<Object> listOfObjects = new ArrayList<Object>();
for(Object obj: listOfObjects){
   if(obj instanceof String){
   }else if(obj instanceof Integer){
   }etc...
}
于 2011-10-13T14:35:50.970 に答える
5
import java.util.ArrayList;

/**
 * @author potter
 *
 */
public class storeAny {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<Object> anyTy=new ArrayList<Object>();
        anyTy.add(new Integer(1));
        anyTy.add(new String("Jesus"));
        anyTy.add(new Double(12.88));
        anyTy.add(new Double(12.89));
        anyTy.add(new Double(12.84));
        anyTy.add(new Double(12.82));

        for (Object o : anyTy) {
            if(o instanceof String){
                System.out.println(o.toString());
            } else if(o instanceof Integer) {
                System.out.println(o.toString());   
            } else if(o instanceof Double) {
                System.out.println(o.toString());
            }
        }
    }
}
于 2013-02-15T14:42:23.603 に答える
4

Just call .getClass() on each Object in a loop.

Unfortunately, Java doesn't have map(). :)

于 2008-09-19T23:20:35.267 に答える
3

Instanceof は、特定のクラスに依存しない場合に機能しますが、リストに null を含めることができることに注意してください。そのため、obj.getClass() は失敗しますが、instanceof は null に対して常に false を返します。

于 2008-09-20T00:04:53.990 に答える
3

Java 8以降


        mixedArrayList.forEach((o) -> {
            String type = o.getClass().getSimpleName();
            switch (type) {
                case "String":
                    // treat as a String
                    break;
                case "Integer":
                    // treat as an int
                    break;
                case "Double":
                    // treat as a double
                    break;
                ...
                default:
                    // whatever
            }
        });

于 2015-05-10T11:12:57.727 に答える
2

instead of using object.getClass().getName() you can use object.getClass().getSimpleName(), because it returns a simple class name without a package name included.

for instance,

Object[] intArray = { 1 }; 

for (Object object : intArray) { 
    System.out.println(object.getClass().getName());
    System.out.println(object.getClass().getSimpleName());
}

gives,

java.lang.Integer
Integer
于 2015-02-05T18:06:26.443 に答える
0

あなたは「これは書かれたJavaコードの一部です」と言いますが、それから、別の方法で設計できる可能性がまだあると推測します。

ArrayList を持つことは、もののコレクションを持つようなものです。リストからオブジェクトを取得するたびに instanceof または getClass を強制するのではなく、DB からオブジェクトを取得するときにオブジェクトの型を取得し、適切な型のコレクションに格納するようにシステムを設計してみませんか?物体?

または、これを行うために存在する多くのデータ アクセス ライブラリの 1 つを使用することもできます。

于 2008-09-20T01:11:36.280 に答える
0

データが何らかの形式の数値であると予想され、結果を数値に変換することに関心がある場合は、次のことをお勧めします。

for (Object o:list) {
  Double.parseDouble(o.toString);
}
于 2008-12-11T14:56:40.033 に答える