This week's book giveaway is in the NodeJS forum. We're giving away four copies of Serverless Applications with Node.js and have Slobodan Stojanovic & Aleksandar Simovic on-line! See this thread for details.
If you need reflection to inspect your arguments you need a better design. Can't you introduce one or more interfaces that your classes can implement, and that you can use in your method? Using instanceof and casting is a much nicer way than using reflection.
Rob Spoor wrote:. . . instanceof and casting is a much nicer way than using reflection.
But there is bound to be a better way to do things than instanceof, which is usually another “code small”. I would start by no longer using java.util.Date or Calendar.
posted 6 months ago
Ron McLeod wrote:Do you want to know what type of object was passed to your method?
I was thinking of having a method that takes an argument of type Object. Then, I would like to find out whether that object has any properties of type Date or Calendar. For example, if a Car object were passed to the method, I would like to find out if the Car object has any properties of type Date or Calendar. If a Person object were passed to the method, I would like to find out if the Person object has any properties of type Date or Calendar.
Fred Victa wrote:
Suppose the properties are private. If the field is of type Date or Calendar and it is not null, how can I convert the timestamp to UTC?
The java.lang.reflect.Field object has setters. So, you can set the value of the field too.
However, keep in mind, you will need permission. If there is a security manager, and your application don't have the rights, the operation will fail (also you can request access to private fields via the setAccessible() method call too, which can also fail if the security manager doesn't allow it).
Rob Spoor wrote:What do you need to do with these properties?
If they are of type Date or Calendar and they are not null, then convert the timestamp to UTC.
The properties are private.
How do you know the properties are private? You asked about getting date or calendar properties from objects of arbitrary classes, so those properties could have any level of accessibility. And what if the class has several date properties?
Or if you just have a specific list of classes you're interested in here, let's bring up the idea of making those classes implement a specific interface again.