2

私のコードは次のとおりです。

    System.out.println("This will save a table to XML data sheet.");
    System.out.println("Please pick a table to save: " + listOfTables.toString());
    command = scan.nextLine();
    if(listOfTables.contains(command))
    {
        System.out.println("successfuly found table to save: " + command);
        try  //Java reflection
        {
            Class<?> myClass = Class.forName(command); // get the class named after their input
            Method listMethod = myClass.getDeclaredMethod("list"); // get the list method from the class
            Object returnType = listMethod.invoke(myClass, new Object[]{}); // run the list method
            ArrayList<Object> objectList = (ArrayList)returnType; // get the arraylist of objects to send to XML
            try 
            {
                JAXBContext jaxbContext = JAXBContext.newInstance(myClass);
                Marshaller marshaller = jaxbContext.createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                JAXBElement<?> jaxbElement = new JAXBElement<?>(new QName("jaxbdemo", "generated"), myClass, objectList.get(0));
                marshaller.marshal(jaxbElement, System.out);

            } catch (JAXBException e) {}
        }
        catch (ClassNotFoundException | SecurityException | NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { }

私の問題は、次のどちらでもないことです。

JAXBElement<?> jaxbElement = new JAXBElement<?>(new QName("jaxbdemo", "generated"), myClass, objectList.get(0));

または:

JAXBElement<myClass> jaxbElement = new JAXBElement<myClass>(new QName("jaxbdemo", "generated"), myClass, objectList.get(0));

コンパイルします。では、JAXBElement タイプの <> の間に何を入れる必要がありますか? ところで、私は得ています:

The constructor JAXBElement<myClass>(QName, Class<myClass>, myClass) refers to the missing type myClass

と:

Cannot instantiate the type JAXBElement<?>
4

1 に答える 1

1

これを行うには、ヘルパーメソッドを使用する必要があります。大まかな例を次に示します。

static <T> void helper(Class<T> myClass) {

    Method listMethod = myClass.getDeclaredMethod("list");
    Object returnType = listMethod.invoke(myClass, new Object[]{});
    @SuppressWarnings("unchecked") // [carefully document why this is okay here]
    ArrayList<T> objectList = (ArrayList<T>)returnType;

    ...

    JAXBElement<T> jaxbElement = new JAXBElement<T>(
            new QName("jaxbdemo", "generated"),
            myClass,
            objectList.get(0)
    );

    ...
}

その時点から、あなたは自由に戻るJAXBElement<?>か、ヘルパー内の残りの作業を終えることができます。

前述のように、チェックされていないキャストを文書化して、コードで想定されているように、aでlist表される特定のクラスを呼び出すと必ずが返される理由を説明する必要があります。この方法論は私にはせいぜいもろいように思えます、そしてあなたが電話するとき私はすでに間違いを見つけることができます:Class<T>ArrayList<T>invoke

listMethod.invoke(myClass, new Object[]{});

そのメソッドは、最初の引数として(またはnull静的メソッドの場合)メソッドを呼び出すインスタンスを取りますが、渡すことになりますmyClass-それはおそらく正しくありません。

于 2013-03-01T05:17:53.890 に答える