Instance/object of StackTraceElement ?

Hi
I will appreciate if someone can help.
I would like to create a object of class StackTraceElement. As soon as I do something simple like the following in class A:
StackTraceElement strE = new StackTraceElement();
strE.getClassName();
I get a compiler error "StackTraceElement() has private access in java.lang.StackT...".
I assume the constructor is private. Do I need to implement a interface. WHAT & HOW can I do to overcome this problem?
Thanks for the help
L

While the need to directly generate StackTraceElements is rare, it does exists. Interpreted languages (like Jython) and languages with sources that compile to Java source (like JSP) come to mind. A public constructor will be added in Tiger:
http://developer.java.sun.com/developer/bugParade/bugs/4712607.html
For now, here's another way to construct StackTraceElements.
import java.io.*;
* Static methods for dealing with stack traces.
public class StackTraces {
    private StackTraces() {} // prevent pointless instantiation
     * Create a StackTraceElement using the given arguments.
     * This method is a work-around until StackTraceElement has a public
     * constructor in Tiger.  This is done by using serialization and
     * deserialization, so it should be compatible with SecurityManagers
     * that prohibit reflection.
     * <p>
     * @see <a href="http://developer.java.sun.com/developer/bugParade/bugs/4712607.html">this RFE </a>
     * @param className
     * @param fileName
     * @param lineNumber
     * @param methodName
     * @param isNative (current implementation ignores this)
     * @return the StackTraceElement
    public static StackTraceElement newStackTraceElement(
        String className, String fileName, int lineNumber,
        String methodName, boolean isNative)
        byte[] copy = new byte[TEMPLATE_BYTES.length];
        for (int i=0; i<copy.length; i++)
            copy=TEMPLATE_BYTES[i];
replaceLineNumber(copy,lineNumber);
copy = replace(copy,TEMPLATE.getClassName(), className);
copy = replace(copy,TEMPLATE.getFileName(), fileName);
copy = replace(copy,TEMPLATE.getMethodName(), methodName);
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(copy));
return (StackTraceElement) in.readObject();
} catch (Throwable t) {
t.printStackTrace();
return null;
// the original element that we serialize to use as a template
private static StackTraceElement TEMPLATE;
// the serialized bytes of the template above
private static byte[] TEMPLATE_BYTES;
// offset that the line number is stored at in the serialized bytes
private static int LINE_NUMBER_OFFSET;
* This method creates the inital template bytes.
* A better way to handle this would be to load the bytes as a resource,
* or even to directly encode them into the source as a literal.
* That way we would guarantee a fixed starting point.
static {
try {
// create a template and convert it to serialized bytes
TEMPLATE = StackTraceElementTemplate.methodTemplate();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bytes);
out.writeObject(TEMPLATE);
out.close();
TEMPLATE_BYTES = bytes.toByteArray();
// make sure the bytes are still readable
ObjectInputStream in =
new ObjectInputStream(
new ByteArrayInputStream(TEMPLATE_BYTES));
if (!TEMPLATE.equals(in.readObject()))
throw new IllegalStateException("Unable to verify template");
LINE_NUMBER_OFFSET = findLineNumberOffset();
} catch (Throwable t) {
throw new ExceptionInInitializerError(t);
// Replace the bytes that represent the line number
private static void replaceLineNumber(byte[] bytes, int lineNumber) {
bytes[LINE_NUMBER_OFFSET    ] = (byte) (lineNumber >> 8 & 0xFF);
bytes[LINE_NUMBER_OFFSET + 1] = (byte) (lineNumber & 0xFF);
// Replace the original string with the replacement string
private static byte[] replace(byte[] source, String original, String replacement) {
int offset = startOf(source,getUTF(original));
if (offset<0) {
dumpBytes(source);
throw new IllegalStateException(
original + " not found in " + new String(source));
if (offset + sizeOf(original) > source.length) {
dumpBytes(source);
throw new IllegalStateException(
offset + " not found correctly.");
int sizeDiff = sizeOf(replacement) - sizeOf(original);
byte[] dest = new byte[source.length + sizeDiff];
int destI = 0;
// copy everything up to the replacement string
for (int i=0; i<offset; i++) {
dest[destI] = source[i];
destI++;
// copy the replacement string, instead of the original
for (int i=0; i<sizeOf(replacement); i++) {
dest[destI] = getUTF(replacement)[i];
destI++;
// copy everything after the replacement string
int tail = offset + sizeOf(original);
for (int i=tail; i<source.length; i++) {
dest[destI] = source[i];
destI++;
return dest;
// Dump these bytes in a quasi-readable format
private static void dumpBytes(byte[] bytes) {
for (int i=0; i<bytes.length; i++) {
byte b = bytes[i];
String hex = Integer.toHexString(b & 0xFF);
System.out.println(i + " " + hex + " " + new String(new byte[] ));
// find the start of part within whole
private static int startOf(byte[] whole, byte[] part) {
int wholeI = 0; // whole index
int partI = 0; // part index
while (wholeI<whole.length) {
if (whole[wholeI]==part[partI]) {
wholeI++;
partI++;
if (partI>=part.length)
return wholeI - part.length;
} else {
wholeI++;
partI = 0;
return -1; // not found
private static int sizeOf(String s) {
return getUTF(s).length;
private static byte[] getUTF(String s) {
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bytes);
out.writeUTF(s);
out.close();
return bytes.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
private static int findLineNumberOffset() {
* This number was generated by eyeballing the dump.
* A serialization guru could provide a better way of getting it.
return 135;
// This class is just used to generate a template StackTraceElement
private static final class StackTraceElementTemplate {
private static StackTraceElement methodTemplate() {
return new Throwable().getStackTrace()[0];
} // Stack Trace Element Template
public static void main(String[] args) {
dumpBytes(TEMPLATE_BYTES);
System.out.println(newStackTraceElement(
"ClassName","FileName.java",42,"methodName",true));
System.out.println(newStackTraceElement(
"X","Y",0,"Z",true));
String LONG =
"ReallyReallyReallyReallyReallyReallyReallyReallyReally" +
"ReallyReallyReallyReallyReallyReallyReallyReallyReally" +
"ReallyReallyReallyReallyReallyReallyReallyReallyReally" +
"Long"
System.out.println(newStackTraceElement(
LONG + "X", LONG + "Y",60000,LONG + "Z",true));
} // Stack Traces

Similar Messages

  • Synchronizing on Process Instance Object

    Hi,
    We have a process web service, which is used to create, notify and update BPM process instances.
    This process web service is accessed from Java code.
    The java code uses a re-try mechanism to talk to the process web service.
    We want this to be changed using wait-notify. But we have only the string value for Process Instance ID.
    Can anybody help me on how could we get the BPM process instance object with the Process Instance ID?
    I hope for this case we should synchronize on the BPM process Instance Object.
    Please find below the current code snippet with re-try which needs to be changed as wait-notify.
    for(int i = retryCount; i >= 0; i--) {
    try {
    sResult = wsClient.notifyUpdate(oEvent, oTG, sInstId);
    break;
    catch(Exception e) {
    if(i == 0) {
    throw e;
    logger.error(getClass().getName() + " - Failed to call wsClient.notifyUpdate()");
    try {
    logger.info(getClass().getName() + " - Retrying bpmUpdateProcessInstance ... " + (retryCount - i + 1) + " times in "
    + (System.currentTimeMillis() - startTimeMillis) + " millis.");
    Thread.sleep(retryInterval);      
    catch(InterruptedException ignore) {
         //silent catch is fine here
    }// end for loop

    Hi,
    Please correct me if I miss-understood your question.
    You want to know the process instance Id of a particular BPM process ?
    You want to do it through java code or in BPM process layer ?
    Which version of OBPM/ALBPM you are using ?
    Bibhu

  • Multiple Instances Object Calling Getting #1009 Error

    Hi,
    I believe this has to be a logical explanation for this. I have the code here as follows:
    private function action():void{
        thematicMap.passBox(canvas,regions);
        thematicMap.drawthematicMap.passBox(canvas);  
        //Setting the Canvas
        thematicMap.setCanvas(0,0,30,50);     
        thematicMap.drawthematicMap.draw(regions);
        thematicMap.setCanvas(24,24,453,455);
        thematicMap.drawthematicMap.draw(regions);     
    This does show two instances of the thematicMaps, which is what works in main.zip. However, what I really want to do is this:
    private function action():void{
        thematicMap.passBox(canvas,regions);
        thematicMap.drawthematicMap.passBox(canvas); 
                   a = new ThematicMap();
       b = new ThematicMap();  
        //Setting the Canvas
        a.setCanvas(0,0,30,50);
                    b.setCanvas(24,24,453,455);     
                   //Draw
                  a.drawthematicMap.draw(regions);
      b.drawthematicMap.draw(regions);     
    The output of the application below is only a blank screen. I then investigated and added some try and catch clauses to see what errors there are,
    try {
             //Setting the Canvas
         a.setCanvas(0,0,30,50);     
         b.setCanvas(24,24,453,455); 
                  catch (errObject:Error) {Alert.show("An error occurred: " + errObject.message);}
    The results I got was Error #1009. How come that I have provided the parameters and the return is null object of reference?
    Thanks for your help.
    Alice

    To answer your second point regarding if I had added a child to my  canvas to draw, here is the snippet:
    public function draw(arr:Array):void{
                 regions = arr;    
                 component_width = [];
                 component_height= [];       
                 for (var s:String in regions) {
                    trace("\n" + s);
                    shape = new UIComponent();  
                    gr = shape.graphics;
                    gr.lineStyle(3);//Define line style  
                    coords = regions[s];
                    gr.moveTo(coords[0],coords[1]);               
                 for (var i:int = 2; i < coords.length; i += 2) gr.lineTo(coords[i],coords[i + 1]);  
                     trace(coords);                
                     gr.lineTo(coords[0],coords[1]);    //return the code back to the beginning   
                     gr.endFill(); //Put this in if there is a color
                     canvas.addChild(shape);             
    This is what is in my setCanvas function:
    public function setCanvas(x:Number,y:Number,width:Number,height:Number):void{       
                canvas.setActualSize(width,height);
                canvas.x = x;
                canvas.y = y;  
                coordinate_conversion(regions);
                new_coordinate_conversion(regions);
    What else could be wrong here?
    Thanks for your help.
    Alice

  • How to create instance object of Attachments2

    I am trying to add attachments to Activities i.e. contacts. I read in 2005, Attachments2 replaces Attachments.
    1) Just want to to know how to attach documents to Activities using Attachments2.
    2) Or How to create an instance for Attachments2?
    Many Thanks

    I am not sure if I understand your question but anyway this is <u>all</u> described in the SDK help.
    Each of these objects
    Contacts, ContractTemplates, CustomerEquipmentCards, EmployeeInfo, KnowledgeBaseSolutions, Messages, Message, SalesOpportunities, and ServiceContracts.
    has an Attachements property that from 2005 onwards this is an Attachements2 object. So if you get the father object you will get also the attachement collection in memory.

  • Multi-Instance Object Searches

    I want to use OEM 10g - and the table of Preferred Credentials - to be able to search ALL monitored database instances for either all occurences of a particular object type (such as finding all database links) or all objects with a particular name (such as trying to id all instances where a custom package was installed). I have 75 instances to look thru (just in Production) and this would be most helpful
    Can anyone recommend a solution along with steps ?
    Alan

    You can execute sql across multiple databases and view their results>
    select one database>
    Maintenance>
    Execute SQL
    Use the Add button to add additional databases to execute on. Check the keep the execution history for this command.
    Have fun!

  • Getting total number of instances (objects) running in a JVM

    Hello,
    Is there any way to get total number of objects in the heap of a JVM without using any profiling tools like JProbe
    Regards,
    Nikhil.K.R

    Have you looked at the JDK troubleshooting tools, in particular jmap -histo:
    http://java.sun.com/javase/6/docs/technotes/tools/index.html#troubleshoot
    You might also find useful info in the troubleshooting guide:
    http://java.sun.com/javase/6/webnotes/trouble/index.html

  • Error when creating inner instance object...

    public class Outer{
              class Inner{}
              public static void main(String[] s){
               Outer o = new Outer();
               Outer.Inner i = o.new Outer.Inner();
               /*above is what my tutorial has taught me, but when a compile time         error?*/
    }Can any spot the error of the above??

    I'd say the error is in trying to do that in the first place.
    What's the exact error you get when you try to compile?
    As a guess, I'd say that Outer.inner isn't valid because Inner isn't static, just like Outer.foo() wouldn't be valid if you had a non-static method foo(). Just like you'd need to do o.foo(), you probably need to do o.inner.
    Have I just done your homework for you?

  • How to get object/instance name in method

    Hi folks,
    I have created a class and implemented a method within the class.
    Now i would like get the name of instance/object calling this method ,within this method.
    Is their any way to get this obj name within method?
    Eg:
    I hve class ZCL with method METH
    Now in some program i used this method, by creating any obj
              data obj type ref to ZCL
              obj->METH
    Now is there any way to get this obj name within the methodMETH by using some method like GET_OBJ_NAME(just making a guess)
    Regards
    PG

    >
    PG wrote:
    > Now is there any way to get this obj name within the methodMETH by using some method like GET_OBJ_NAME(just making a guess)
    >
    > Regards
    > PG
    Please check the below code snippet
      DATA:
        lref_obj TYPE REF TO cl_abap_typedescr.
      lref_obj ?= cl_abap_objectdescr=>describe_by_object_ref( me ).

  • Reference object/element on an instance

    Is it possible to control an object/element on a instance? If so, how is it done through actionscript? There is an instance "instance140" off of the root, that has an element named img4 that i need to reference... does anyone know how I would go about that? 
    using root.instance.object form returns undefined. Please help.

    you can use the following (but you should type your object correctly):
    var yourobject:* = MovieClip(root).instance140.getChildByName("img4");

  • PDF - Text on multiple lines become seperate objects - is there a way to prevent this?

    I'm exporting to PDF from inDesign with the idea that the text would be editable with Acrobat Pro.
    However, when opening the PDF in Acrobat Pro, each line is a seperate instance / object.
    Is there a way around this?
    I imagine I can recreate the text in Acrobat Pro - but it would be good if there was a way round from inDesign - as i imagine it would be better for SEO and screen readers. Also, i've uploaded PDFs to sites before like Slideshare, yudu, issuu which create a text only version - only the text only version is scr*wed up due to the above problemo.
    Help much appreciated or even to know if its not possible. Thanks.

    Not really sure what SEO has to do with it? But I think  you're talking about "Accessibility"
    When a PDF is created that's what happens. You can't export it and have paragraphs of text editable. PDFs are meant to be FINAL files.
    For accessiblity follow these tips -
    http://www.adobe.com/accessibility/products/acrobat/
    http://tv.adobe.com/watch/accessibility-adobe/preparing-indesign-files-for-accessibility/
    http://tv.adobe.com/watch/accessibility-adobe/acrobat-tagging-pdf-content-as-a-table/
    http://indesignsecrets.com/creating-accessible-pdf-documents.php

  • How to reach a method of an object from within another class

    I am stuck in a situation with my program. The current situation is as follows:
    1- There is a class in which I draw images. This class is an extension of JPanel
    2- And there is a main class (the one that has main method) which is an extension of JFrame
    3- In the main class a create an instance(object) of StatusBar class and add it to the main class
    4- I also add to the main class an instance of image drawing class I mentioned in item 1 above.
    5- In the image drawing class i define mousemove method and as the mouse
    moves over the image, i want to display some info on the status bar
    6- How can do it?
    7- Thanks!

    It would make sense that the panel not be forced to understand its context (in this case a JFrame, but perhaps an applet or something else later on) but offer a means of tracking.
    class DrawingPanel extends JPanel {
      HashSet listeners = new HashSet();
      public void addDrawingListener(DrawingListener l) {
         listeners.add(l);
      protected void fireMouseMove(MouseEvent me) {
         Iterator i = listeners.iterator();
         while (i.hasNext()) {
            ((DrawingListener) i.next()).mouseMoved(me.getX(),me.getY());
    class Main implements DrawingListener {
      JFrame frame;
      JLabel status;
      DrawingPanel panel;
      private void init() {
         panel.addDrawingListener(this);
      public void mouseMoved(int x,int y) {
         status.setText("x : " + x + " y: " + y);
    public interface DrawingListener {
      void mouseMoved(int x,int y);
    }Of course you could always just have the Main class add a MouseMotionListener to the DrawingPanel, but if the DrawingPanel has a scale or gets embedded in a scroll pane and there is some virtual coordinate transformation (not using screen coordinates) then the Main class would have to know about how to do the transformation. This way, the DrawingPanel can encapsulate that knowledge and the Main class simply provides a means to listen to the DrawingPanel. By using a DrawingListener, you could add other methods as well (versus using only a MouseMotionListener).
    Obviously, lots of code is missing above. In general, its not a good idea to extend JFrame unless you really are changing the JFrames behavior by overrding methods, etc. Extending JPanel is okay, as you are presumably modifiying the drawing code, but you'd be better off extending JComponent.

  • SQL Server Utility - How to Remove Instance that No Longer Exists on Server

    I had a default instance that I had installed for an application.  But then I was told they wanted it as a named instance.  I had added the default instance to the UCP (SQL Server Utility).  I have uninstalled the default instance forgetting
    that I had added it to the UCP.  Now when I try to remove the managed instance I get the following error:
    The action has failed.  Step failed.  The SQL Server connection does not correstpond to this managed instance object.  (Microsoft.Sqlserver.Management.Utility)
    How do I remove the managed instance from the UCP?  Do I need to go into a table in database sysutility_mdw and delete something?
    select * from msdb.dbo.sysutility_ucp_managed_instances
    where instance_id=57
    Maybe delete from table msdb.dbo.sysutility_ucp_managed_instances?
    Or maybe table sysutility_ucp_managed_instances_internal?
    lcerni

    I ran this
    EXEC msdb.dbo.sp_sysutility_ucp_remove_mi @instance_id=57
    And it fixed the issue.
    lcerni

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Parse of a xml file to an java object model

    Hello,
    I'm trying to do a program that receive an xml file and ought to create all the neccesary java objects according to the content of the parsed xml file.
    I've all the class created for all the objects that could be present into the xml and the idea is to go down in the tree of nodes recursively until it returns nodes more simple. Then, I create the last object and while I come back of the recursively calls, I create the objects more complex until I reached to the main object.
    Until now, I have part of this code, that is the one wich have to parse the parts of the xml.
    public static void readFile(String root){
              DocumentBuilderFactory factory = DocumentBuilderFactory
                   .newInstance();
              try {
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   String contents = scanner.next();
                   scanner.close();
                   Document document = builder.parse(new ByteArrayInputStream(contents.getBytes()));
                   Node node = null;
                   NodeList nodes = null;
                   Element element = document.getDocumentElement();
                   System.out.println(element.getNodeName());
                   NodeList subNodes;
                   NamedNodeMap attributes;
                   //if (element.hasAttributes())
                   visitNodes(element);
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
              } catch (SAXException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         private static void visitNodes (Node node){
              for(Node childNode = node.getFirstChild(); childNode!=null;){
                   if (childNode.getNodeType() == childNode.DOCUMENT_NODE){
                        System.out.println("Document node Name " + childNode.getNodeName());
                        visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.ELEMENT_NODE){
                        System.out.println("Node Name " + childNode.getNodeName());
                        if (childNode.hasAttributes()){
                             visitAttributes(childNode.getAttributes());
                        if (childNode.hasChildNodes()){
                             visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.TEXT_NODE && !childNode.getNodeValue().contains("\n\t")){
                        System.out.println("Node value " + childNode.getNodeValue());
                   Node nextChild = childNode.getNextSibling();
                   childNode = nextChild;
         private static void visitAttributes(NamedNodeMap attributes){
              Node node;
              for(int i = 0; i < attributes.getLength(); i++){
                   node = attributes.item(i);
                   System.out.print(node.getNodeName() + " ");
                   System.out.print(node.getNodeValue() + " ");
                  }I don't know the use of childNodeType. For example, I expected that the XML tags with childs in his structure, enter by the option NODE_DOCUMENT and the tags without childs by the ELEMENT_NODE.
    But the most important problem I've found are the nodes [#text] because after one ELEMENT_NODE I always found this node and when I ask if the node hasChilds, always returns true by this node.
    Has any option to obtain this text value, that finally I want to display without doing other recursively call when I enter into the ELEMENT_NODE option?
    When one Node is of type DOCUMENT_NODE or DOCUMENT_COMMENT? My program always enter by the ELEMENT_NODE type
    Have you any other suggestions? All the help or idea will be well received.
    Thanks for all.

    Hello again,
    My native language is Spanish and sorry by my English I attemp write as better I can, using my own knowledge and the google traductor.
    I have solved my initial problem with the xml parser.
    Firstly, I read the complete XML file, validated previously.
    The code I've used is this:
    public static String readCompleteFile (String root){
              String content = "";
              try {
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   content = scanner.next();
                   scanner.close();
              } catch (IOException e) {
                   e.printStackTrace();
              return content;
         }Now, I've the file in memory and I hope I can explain me better.
    I can receive different types of XML that could be or not partly equals.
    For this purpose I've created an external jar library with all the possible objects contained in my xml files.
    Each one of this objects depend on other, until found leaf nodes.
    For example, If I receive one xml with a scheme like the next:
    <Person>
        <Name>Juliet</Name>
        <Father Age="30r">Peter</Father>
        <Mother age="29">Theresa</Mother>
        <Brother>
        </Brother>
        <Education>
            <School>
            </school>
        </education>
    </person>
    <person>
    </person>The first class, which initializes the parse, should selecting all the person tags into the file and treat them one by one. This means that for each person tag found, I must to call each subobject wich appears in the tag. using as parameter his own part of the tag and so on until you reach a node that has no more than values and or attributes. When the last node is completed I'm going to go back for completing the parent objects until I return to the original object. Then I'll have all the XML in java objects.
    The method that I must implement as constructor in every object is similar to this:
    public class Person{
      final String[] SUBOBJETOS = {"Father", "Mother", "Brothers", "Education"};
      private String name;
         private Father father;
         private Mother mother;
         private ArrayList brothers;
         private Education education;
         public Person(String xml){
           XmlUtil utilXml = new XmlUtil();          
              String xmlFather = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[0]);
              String xmlMother = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[1]);
              String xmlBrothers = utilXml.textBetweenMultipleXmlTags(xml, SUBOBJETOS[2]);
              String xmlEducation = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[3]);
              if (!xmlFather.equals("")){
                   this.setFather(new Father(xmlFather));
              if (!xmlMother.equals("")){
                   this.setMother(new Father(xmlMother));
              if (!xmlBrothers.equals("")){
                ArrayList aux = new ArrayList();
                String xmlBrother;
                while xmlBrothers != null && !xmlBrothers.equals("")){
                  xmlBrother = utilXml.textBetweenXmlTags(xmlBrothers, SUBOBJETOS[2]);
                  aux.add(new Brother(xmlBrother);
                  xmlBrothers = utilXml.removeTagTreated(xmlBrothers, SUBOBJETOS[2]);
                this.setBrothers(aux);
              if (!xmlEducation.equals("")){
                   this.setEducation(new Father(xmlEducation));     
    }If the object is a leaf object, the constructor will be like this:
    public class Mother {
         //Elements
         private String name;
         private String age;
         public Mother(String xml){          
              XmlUtil utilXml = new XmlUtil();
              HashMap objects = utilXml.parsearString(xml);
              ArraysList objectsList = new ArrayList();
              String[] Object = new String[2];
              this.setName((String)objects.get("Mother"));
              if (objects.get("attributes")!= null){
                   objectsList = objects.get("attributes");
                   for (int i = 0; i < objectsList.size();i++){
                     Object = objectsList.get(i);
                     if (object[0].equals("age"))
                       this.setAge(object[1]);
                     else
         }Each class will have its getter and setter but I do not have implemented in the examples.
    Finally, the parser is as follows:
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.xml.sax.SAXException;
    public class XmlUtil {
         public HashMap parsearString(String contenido){
              HashMap objet = new HashMap();
              DocumentBuilderFactory factory;
              DocumentBuilder builder;
              Document document;
              try{
                   if (content != null && !content.equals("")){
                        factory = DocumentBuilderFactory.newInstance();
                        builder = factory.newDocumentBuilder();
                        document = builder.parse(new ByteArrayInputStream(content.getBytes()));
                        object = visitNodes(document);                    
                   }else{
                        object = null;
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
                   return null;
              } catch (SAXException e) {
                   e.printStackTrace();
                   return null;
              } catch (IOException e) {
                   e.printStackTrace();
                   return null;
              return object;
         private HashMap visitNodes (Node node){
              String nodeName = "";
              String nodeValue = "";
              ArrayList attributes = new ArrayList();
              HashMap object = new HashMap();
              Node childNode = node.getFirstChild();
              if (childNode.getNodeType() == Node.ELEMENT_NODE){
                   nodeName = childNode.getNodeName();                    
                   if (childNode.hasAttributes()){
                        attributes = visitAttributes(childNode.getAttributes());
                   }else{
                        attributes = null;
                   nodeValue = getNodeValue(childNode);
                   object.put(nodeName, nodeValue);
                   object.put("attributes", attributes);
              return object;
         private static String getNodeValue (Node node){          
              if (node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE && !node.getFirstChild().getNodeValue().contains("\n\t"))
                   return node.getFirstChild().getNodeValue();
              else
                   return "";
         private ArrayList visitAttributes(NamedNodeMap attributes){
              Node node;
              ArrayList ListAttributes = new ArrayList();
              String [] attribute = new String[2];
              for(int i = 0; i < attributes.getLength(); i++){
                   atribute = new String[2];
                   node = attributes.item(i);
                   if (node.getNodeType() == Node.ATTRIBUTE_NODE){
                        attribute[0] = node.getNodeName();
                        attribute[1] = node.getNodeValue();
                        ListAttributes.add(attribute);
              return ListAttributes;
    }This code functioning properly. However, as exist around 400 objects to the xml, I wanted to create a method for more easily invoking objects that are below other and that's what I can't get to do at the moment.
    The code I use is:
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class UtilClasses {
         public Object UtilClasses(String package, String object, String xml){
              try {
                Class class = Class.forName(package + "." + object);
                //parameter types for methods
                Class[] partypes = new Class[]{Object.class};
                //Create method object . methodname and parameter types
                Method meth = class.getMethod(object, partypes);
                //parameter types for constructor
                Class[] constrpartypes = new Class[]{String.class};
                //Create constructor object . parameter types
                Constructor constr = claseObjeto.getConstructor(constrpartypes);
                //create instance
                Object obj = constr.newInstance(new String[]{xml});
                //Arguments to be passed into method
                Object[] arglist = new Object[]{xml};
                //invoke method!!
                String output = (String) meth.invoke(dummyto, arglist);
                System.out.println(output);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
              return null;
         }This is an example obtained from the Internet that I've wanted modified to my needs. The problem is that when the class calls this method to invoke the constructor and does not fail, this does not do what I expect, because it creates an empty constructor. If not, the parent class gives a casting error.
    I hope that now have been more clear my intentions and that no one has fallen asleep reading this lengthy explanation.
    greetings.

  • Creation of DTO object from Azure SDK 2.4 CreateQuery

    HI,
    I looking generic approach for performing Server side project and resolve with Entity Resolve class Method. Does any1 has good example for converting Azure Table Instance (Object) to DTO object.
    For example to implement DTO object in Azure SDK 2.4 Table Storage. I saw some sample like Resolve(EntityAdapter.AdapterResolver> but looks like conversion happen on Client not on server side. Table Service pulls all the properties of an entity to client
    side and filers required properties @ client. I'm looking for generic approach where I get entity with only required properties from server side projections i.e send only required properties to client this will reduce load, since less payload.
    When i try to use TableQuery<DynamicTableEntity>().where (<Predicate>)
    where Predicate is expected in format FUNC<T,Bool> where T is of type DynamicTableEnitty. But i cant pass of type DynamicTableEntity,can we pass instead of DynamicTableEntity with ITableEntity .
    Mahender

    Hi,
    >>I'm looking for generic approach where I get entity with only required properties from server side projections
    As far as I know, If we want to get the entity with required properties, we could consider use SelectColumns Property, refer to
    http://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.tablequery.selectcolumns.aspx for more details, the code below may give you some tips.
    TableQuery<CustomerEntity> tquery = new TableQuery<CustomerEntity>();
    List<string> cloumns = new List<string>();
    cloumns.Add("PhoneNumber");
    tquery.SelectColumns = cloumns;
    var result = cloudTable.ExecuteQuery(tquery);
    Best Regards,
    Jambor
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

Maybe you are looking for

  • Safari is crashing immediately when I try to open

    PLEASE EXPLAIN SLOWLY... Process:         Safari [664] Path:            /Applications/Safari.app/Contents/MacOS/Safari Identifier:      com.apple.Safari Version:         7.0.2 (9537.74.9) Build Info:      WebBrowser-7537074009000000~3 Code Type:     

  • Obtaining the full file path specification from Flash Movie and QuickTime icons?

    How do you obtain the full file path specification from Flash Movie and QuickTime icons? I want the path and the file name that is contained in these icons. I am using a "dive" to run through the icons of a file, and when I come upon these two types

  • Have a question about WSGEN

    hi,all i am a beginner, now step by step doing a test based on your article. in building process,BUILD FAILED,say "could not create task of type:wsgen.Common solutions are to use taskdef to declare your task,or, if this is an optional task, to put th

  • PS to PDF generation distorted

    Hi We are generating PS to PDF via 3b2 platform. While generating the pdf, the pdfs were distorted. Can anyone help me to sort out this kind of issue. I have the problem pdf in my hand and i am not able to attach. Thanks for all your help. Regards, S

  • WSDL Eclispe VS WebSphere Client Generation

    Hi All, I am facing issues while generating WSDL Clients on WebSphere plateform. After generating the clients I am not able to execute the UCM services. While when i generate the WSDL Client from Eclispe, I can successfully execute UCM Services. Any