user2559108
user2559108

Reputation:

Access Java anonymous object properties

I am relatively new to Java programming, i am trying to access an anonymous objects properties, this is my object:

Object tomorowWeekday = convertedTimeForAndroid(openHours, tomorrow);

Inspected via the debugger, it looks as this: enter image description here

I need to access the key value pair "to" and "from", there is no method such as tomorrowWeekday.get("from").

How would I access these values in an anonymous object?

Upvotes: 1

Views: 599

Answers (2)

user3753103
user3753103

Reputation: 1

The fields and methods you can access on an object depend on the type of the variable that you use to it. In your code above, you are using a variable Object type, which does not have any knowledge of your nameValuePairs attribute. You'll need to change the type of your reference to something more representative of your actual object. Your debugger is saying that nameValuePairs is of type JSONObject so if you reference with a JSONObject variable, you'll be able to access it using the api specified here: http://www.json.org/javadoc/org/json/JSONObject.html

Upvotes: 0

chiastic-security
chiastic-security

Reputation: 20520

Change to

JSONObject tomorowWeekday = convertedTimeForAndroid(openHours, tomorrow);

You're currently setting the declared type to Object. That means that you can't see any methods other than ones exposed by Object, even though the actual type is JSONObject. Make the declared type the same as the actual type and you'll be able to see all the methods you need.

Because JSONObject is a subclass of Object (as indeed every class is), your current code is legal, but it means you abstract away any functionality that isn't present in Object. This is sometimes a useful trick, but not one to employ unless you know why you're doing it.

(As a side note, the word anonymous is not quite appropriate here. It isn't anonymous: its name is tomorrowWeekday.)

Upvotes: 2

Related Questions