How do i find out the Structure of a Java Object?
I am working with the HttpExcha开发者_StackOverflow中文版nge class, and want to use the getAttribute function to get the POST parameters. If i just call the function and print the results it works. But there has to be some better way to access the returned object and get the contained data.
The Manual is here: http://download.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpExchange.html#getAttribute%28java.lang.String%29
How can i access the Object? Which methods does it have?
I am not familiar with this API, but it appears that HttpExchange.getAttribute is not the method you would use to get POST parameters. Rather it is a mechanism for sharing information within a chain of Filters. Since you would implement the Filters, you would document and understand the attributes that can be stored.
To read the POST details, wouldn't you do HttpExchange.getRequestBody?
Use Java Reflection. Using reflection you could do something like this
Class c = Class.forName("YourClassName");
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++)
System.out.println(m[i].toString()); //iterate through these methods to find out data
The HttpExchange returns you the type Object
for the given attribute name, It is assumed that the one who try to retrieve the attribute knows the type of the attribute and can downcast the Object to appropriate class. E.g. -
String attrValue = (String) httpExchangeObject.getAttribute("nameOfTheAttribute");
you don't need to use reflection on the returned object to find out the structre.. I feel simple down-casting should solve the purpose.
I'm not familiar with this API either. The request POST parameters should be available in raw, unparsed form from getResponseBody()
. However, if you know that the getAttribute method will contain the data you need, but you don't know which class it will have (I don't know how you would know the former without knowing the latter, but anyway), you can use reflection to print the name of the class:
System.out.println (foo.getAttribute("name").getClass ());
If it turns out to be an internal, undocumented class, you can then use more reflection (or other techniques) to look at the class hierarchy until you find a publicly-documented class or interface that you can use.
But this shouldn't be necessary because what you need should be documented somewhere.
精彩评论