Dynamically creating classes in Java

Possible duplicate:
Dynamically create classes in Java

I have a query regarding the concept of Reflection in Java.

I am trying to create a SAX XML parser in Java. What needs to be done, so I need to create a new class containing the fields according to XML, and use the class during parsing. But this method will be very specific to the selected XML.

What I'm thinking about, is there a way I can write an XML parser (SAX) that works with all possible XML? that is, I need to create a class with fields contained in XML dynamically and use the same class to parse the XML file.

I hope I could clearly state my question.

Thanks.

+4
source share
1 answer

I had a similar situation before, but my XML parser needed some configuration. My approach was: a) parsing, b) configuration.

The configuration part builds around XPath expressions that are passed through properties. This is a static XPath expression and needs to be updated if the input XML message changes.

Part of the parsing engine executes these expressions to query the xml element, attribute, etc. to populate a java object.

EDIT:

For example, given xml (simplified, without namespace):

<msg> <something> <somenode> <version>1.0.0</version> </somenode> </something> </msg> 

Code example: (simplified)

 String myXpExpr = "//version/text()"; // make it .properties Document xmlDocument = DocumentBulderFactory.newInstance().newDocumentBuilder().parse(xmlInputStream); XPath xpXPath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpXPath.compile(myXpExpr); resultObject = expr.evaluate(xmlDocument, returnTypeQName); 

This will give you "1.0.0" as resultObject.

0
source

Source: https://habr.com/ru/post/1438479/


All Articles