How do I change this generic class, so the main method can work?

Viewed 51

I have this method in a class

 @Override
    public Optional<T> parse (String fileString, Class someClass) {

        File file = new File(fileString);

        Class smclass= new Class();
        try {
            smclass= (Class) getUnmarshaller().unmarshal(file);
        } catch (JAXBException  e) {
            e.printStackTrace();
        }
        return (Optional<T>) Optional.ofNullable(smclass);
    }

and main method:

        XmlService xmlParser = XmlServiceImpl.getInstance();
        Optional<class> smclass= xmlParser.parse("File.xml", smclass.class);
        System.out.println(smclass);

I want to change the class method so I can call different classes in the main method, not only one, but I don't know how. For example:

        XmlService xmlParser = XmlServiceImpl.getInstance();
        Optional<**class**> **class**= xmlParser.parse("xmlFile.xml", **class**.class);
        System.out.println(**class**);
1 Answers

Another edit: Removed the type parameter from the method EDIT(again): If you don't need to instantiate T(which I believe you don't), you can do what's below. If the API isn't under your control, then you'll have to write Class instead of Class<T> and cast.

    @Override
    public Optional<T> parse (String fileString, Class<T> someClass) {

        File file = new File(fileString);

        T t = null;
        try {
            t = (T) getUnmarshaller().unmarshal(file);
        } catch (JAXBException  e) {
            e.printStackTrace();
        }
        return (Optional<T>) Optional.ofNullable(t);
    }

If you do need a Class object for the unmarshaller to know what kind of object to make, then the only way you can do it is with reflection (that's the nature of the Class class. Also, I'm pretty sure JAXB uses reflection internally anyways and it's all unsafe.

Also, it doesn't seem as if you're using someClass, so you could probably have a method with only the first parameter. But since you are overriding some method in a superclass, you might just have to try what's above.

Related