[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

Question
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

6.8

Java Reflection Invoking methods with primitive data types

Asked by dolphin_g in Java Standard Edition, JAXP & SAX (XML APIs), Java Programming Language, Extensible Markup Language (XML)

Tags: Java, reflection, xml

Hi,

I'm trying to write an application to run on app startup to lad values from XML file to
static java members. When I try to invoke a static java method with a primitive boolean
as  parameter it fails with the below stacktrace.

Root element of the doc is configuration
Total no of classes : 3
Class Name : com.tsswireless.application.dispatch.config.SpeedMatrixConfiguration
Variable :refPointX value :31.14 type :java.lang.Double
setRefPointX
Variable :refPointY value :108.36 type :java.lang.Double
setRefPointY
Variable :speedMatrixID value :01 type :java.lang.String
setSpeedMatrixID
Class Name : com.tsswireless.application.dispatch.config.CacheConfiguration
Variable :addressInfoFlag value :1 type :boolean
java.lang.NullPointerException
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
      at java.lang.reflect.Method.invoke(Method.java:585)
      at com.tsswireless.application.dispatch.config.LoadConfiguration.main(LoadConfiguration.java:83)

The XML file is :

<?xml version="1.0" encoding="UTF-8"?>

<configuration>
      <class>
            <name>com.tsswireless.application.dispatch.config.SpeedMatrixConfiguration</name>
            <variable>
                  <name>refPointX</name>
                  <value>31.14</value>
                  <type>java.lang.Double</type>
            </variable>
            <variable>
                  <name>refPointY</name>
                  <value>108.36</value>
                  <type>java.lang.Double</type>
            </variable>
            <variable>
                  <name>speedMatrixID</name>
                  <value>01</value>
                  <type>java.lang.String</type>
            </variable>
      </class>
      <class>
            <name>com.tsswireless.application.dispatch.config.CacheConfiguration</name>
            <variable>
                  <name>addressInfoFlag</name>
                  <value>1</value>
                  <type>boolean</type>
            </variable>
            <variable>
                  <name>loadInfoFlag</name>
                  <value>1</value>
                  <type>boolean</type>
            </variable>
      </class>            
      <class>
            <name>com.tsswireless.application.dispatch.config.CostParameterConfiguration</name>
            <variable>
                  <name>directDistanceRatio</name>
                  <value>23.45</value>
                  <type>java.lang.Double</type>
            </variable>
      </class>
</configuration>

How do I resolve this? Also, is this the best way to do it? I'm trying to dynamically load values from the XML file. With this approach just creatign the java classes
and mentioning the package path should be good enough to load the values into the app.

Thanks,
Raja
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
/**
 * 
 */
package com.tsswireless.application.dispatch.config;
 
import java.io.File;
import java.lang.reflect.Method;
 
import org.w3c.dom.*;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; 
 
/**
 * <strong>LoadConfiguration</strong>, loads configuration parameters from StateManagerConfig.xml to its appropriate 
 * Class files.
 * 
 * @author Rama
 *
 */
public class LoadConfiguration {
 
	    public static void main (String argv []){
	    try {
 
	            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
	            Document doc = docBuilder.parse (new File("conf/StateManagerConfig.xml"));
 
	            // normalize text representation
	            doc.getDocumentElement ().normalize ();
	            System.out.println ("Root element of the doc is " + 
	                 doc.getDocumentElement().getNodeName());
 
 
	            NodeList classList = doc.getElementsByTagName("class");
	            int totalNoOfClasses = classList.getLength();
	            System.out.println("Total no of classes : " + totalNoOfClasses);
 
	            for(int s=0; s<classList.getLength() ; s++){
 
	                Node classNode = classList.item(s);
	                if(classNode.getNodeType() == Node.ELEMENT_NODE){
	                	
	                    Element classElement = (Element)classNode;
 
	                    //-------
	                    NodeList nameList = classElement.getElementsByTagName("name");
	                    Element classNameElement = (Element)nameList.item(0);
 
	                    String className = ((Node)classNameElement.getChildNodes().item(0)).getNodeValue().trim();
	                    System.out.println("Class Name : " + className );
	                    
	                    NodeList variableList = classElement.getElementsByTagName("variable");
	                    for(int i=0;i<variableList.getLength();i++){
	                    	Element variableElement = (Element)variableList.item(i);
	                    	NodeList variableNameList = variableElement.getElementsByTagName("name");
	                    	String variableNameElement = ((Node)variableNameList.item(0).getChildNodes().item(0)).getNodeValue().trim();
	                    	
	                    	NodeList variableValueList = variableElement.getElementsByTagName("value");
	                    	String variableValueElement = ((Node)variableValueList.item(0).getChildNodes().item(0)).getNodeValue().trim();
	                    	
	                    	NodeList variableTypeList = variableElement.getElementsByTagName("type");
	                    	String variableTypeElement = ((Node)variableTypeList.item(0).getChildNodes().item(0)).getNodeValue().trim();
	                    	
	                    	System.out.println("Variable :"+variableNameElement+ " value :"+variableValueElement
	                    			+" type :"+variableTypeElement);
	                    	
	                    	Class classtype = ClassLoader.getSystemClassLoader().loadClass(className);
	                    	
	                    	Method method1 = classtype.getMethod("set"+ variableNameElement.substring(0, 1).toUpperCase() +
		                    		variableNameElement.substring(1,variableNameElement.length()), getObjectType(variableTypeElement));
	                    	
	                    	if(variableTypeElement.equalsIgnoreCase("boolean")){
	                    		boolean value = false; 
	                    		if(variableValueElement.equals("true") || variableValueElement.equals("false")){
	            	    			value = variableValueElement.equalsIgnoreCase("true")?true:false;
	            	    		} else {
	            	    			value = variableValueElement.equalsIgnoreCase("1")?true:false;
	            	    		} 
	                    		method1.invoke(null, value);
	                    	} else {
	                    		method1.invoke(null, convertToObject(variableTypeElement, variableValueElement));
	                    	}
	                    	
	                    	System.out.println(method1.getName());
	                    }
 
 
	                }//end of if clause
 
 
	            }//end of for loop with s var
 
 
	        } catch (SAXParseException err) {
		        System.out.println ("** Parsing error" + ", line " 
		             + err.getLineNumber () + ", uri " + err.getSystemId ());
		        System.out.println(" " + err.getMessage ());
	        } catch (SAXException e) {
		        Exception x = e.getException ();
		        ((x == null) ? e : x).printStackTrace ();
	        } catch (Throwable t) {
	            t.printStackTrace ();
	        }
	        //System.exit (0);
 
	    }//end of main
	    
	    private static Object convertToObject(String dataType, String value) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
	    	
	    	Object obj = null;
	    	if(dataType.equals("boolean")){
	    		
	    	} else {
	    		Class temp = Class.forName(dataType);
	    		if(temp == Double.class){
	    			obj = Double.valueOf(value);
	    		} else if(temp == Integer.class){
	    			obj = Integer.valueOf(value);
	    		} else if(temp == Short.class){
	    			obj = Short.valueOf(value);
	    		} else if(temp == Long.class){
	    			obj = Long.valueOf(value);
	    		} else if(temp == Float.class){
	    			obj = Float.valueOf(value);
	    		} else if(temp == Character.class){
	    			obj = String.valueOf(value);
	    		} else if(temp == Byte.class){
	    			obj = Byte.valueOf(value);
	    		} else if(temp == String.class){
	    			return value;
	    		} else {
	    			throw new UnsupportedOperationException("Unsupported Data type conversion, Type :"+dataType);
	    		}
	    	}
	    	return obj;
	    }
	    
	    private static Class getObjectType(String javaDataType) throws ClassNotFoundException{
	    	if(javaDataType.equals("boolean")){
	    		return java.lang.Boolean.TYPE;
	    	} else if(javaDataType.equals("int")){
	    		return java.lang.Integer.TYPE;
	    	} else if(javaDataType.equals("char")){
	    		return java.lang.Character.TYPE;
	    	} else if(javaDataType.equals("byte")){
	    		return java.lang.Byte.TYPE;
	    	} else if(javaDataType.equals("short")){
	    		return java.lang.Short.TYPE;
	    	} else if(javaDataType.equals("long")){
	    		return java.lang.Long.TYPE;
	    	} else if(javaDataType.equals("float")){
	    		return java.lang.Float.TYPE;
	    	} else if(javaDataType.equals("double")){
	    		return java.lang.Double.TYPE;
	    	} else if(javaDataType.equals("void")){
	    		return java.lang.Void.TYPE;
	    	} else
	    		return Class.forName(javaDataType);
	    	
	    }
 
}
[+][-]08/18/09 07:24 AM, ID: 25123551Accepted Solution

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

About this solution

Zones: Java Standard Edition, JAXP & SAX (XML APIs), Java Programming Language, Extensible Markup Language (XML)
Tags: Java, reflection, xml
Sign Up Now!
Solution Provided By: TimYates
Participating Experts: 1
Solution Grade: B
 
[+][-]08/18/09 07:09 AM, ID: 25123349Administrative Comment

Experts Exchange has a courteous staff of administrators who help members get the most out of the website by means of administrative comments like this one.

Start your 30-day free trial to view this Administrative Comment or ask the Experts your question.

 
[+][-]08/18/09 07:09 AM, ID: 25123352Administrative Comment

Experts Exchange has a courteous staff of administrators who help members get the most out of the website by means of administrative comments like this one.

Start your 30-day free trial to view this Administrative Comment or ask the Experts your question.

 
[+][-]08/18/09 09:48 AM, ID: 25125160Author Comment

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 30-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]08/18/09 12:30 PM, ID: 25126679Expert Comment

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 30-day free trial to view this Expert Comment or ask the Experts your question.

 
 
Loading Advertisement...
20091111-EE-VQP-92 - Hierarchy / EE_QW_EXPERT_20070906