dimanche 8 janvier 2017

Java casting an object passed to method to its original type

I have a list called itemsData of object of class EtcStruct, but the class can differ depending on the file i want to use (the class is full of variables setters and getters):

ObservableList<EtcStruct> itemsData =  FXCollections.observableArrayList();

Im passing it to the method thats supposed to work for any object type i choose and run invoked method from the file.

public static void parseToFile(ObservableList itemsData){
    EtcStruct itemObject = (EtcStruct) itemsData.get(0);
    System.out.print((int)reflectedmethod.invoke(itemObject);
}

Code above works , but what i want to achieve is make the method work without editing it's object type to make it more flexible for whatever structclass i plan to use.

I tried something with passing Struct Class name and .getClass() it returns the original type but i dont know what to do with it to make the new object of itemsData original type and cast the itemsData object.

public static void parseToFile(ObservableList itemsData,Class c){
    Object itemObject = c.newInstance();
    Object newobject = curClass.newInstance();
    newobject = c.cast(itemsList.get(0));
}

Above seemed dumb to me and obviously didnt work.





Aucun commentaire:

Enregistrer un commentaire