java.util.Date cannot be cast to Object[] - java

I'm using java reflection to call methods at runtime. How do I cast a date object into an object array?
ie,
Method m = ....;
Object[] result = (Object[]) m.invoke(...);
public Date getDate() {
return new Date();
}
Would give:
java.lang.ClassCastException: java.util.Date cannot be cast to [Ljava.lang.Object;
Edit: yeah, I should just add it to an Object array instead and return it.

you don't need to as invoke is a varargs method. you can do.
Object result = method.invoke (instance , new Date ());
There is no need to create an array.
If it's the result you want to change you can wrap it, but I suspect there is no real need to do this. I would see if you really need an array

Related

Java template function

I have a function that sometimes has to return a Date other times a DateTime (Joda-Time).
static public <T extends Object> T convertTimeForServer(DateTime toSave) {
DateTime temp = null;
try {
temp = toSave.withZone(DateTimeZone.forID(getServerTimeZone()));
} catch (Exception e) {
}
T toReturn = null;
if (toReturn.getClass().equals(temp)) {
return (T) temp;//Return DATETIME
} else {
return (T) temp.toDate();//Return DATE
}
}
Is it the right approach?
How to use it?
like this (timerHelper is the name of class):
DateTime t = timerHelper.<DateTime>convertTimeForServer(new DateTime());
Date t2 = timerHelper.<Date>convertTimeForServer(new DateTime());
or
DateTime t = (DateTime)timerHelper.convertTimeForServer(new DateTime());
Date t2 = (Date)timerHelper.convertTimeForServer(new DateTime());
And how to use this function instead?
static public <T extends Object> T current_Moment(){
return convertTimeForServer(new DateTime());
}
I suspect you're being too clever trying to use generics here. Because you don't have polymorphism on return types doesn't mean you should resort to generics to try and achieve that effect.
You can implement this simply as two methods: public static Date convertToDateForServer(DateTime toSave) {...} and public static DateTime convertToDateTimeForServer(DateTime toSave) {...}. The calling code seems to know what it wants, so it can simply call the method needed. If there really is a complex commonality to both methods, make a private method that both can call internally.
If Java 8 is available you could always implement an Either using the new Optional class.
This is one of the tricky areas of Generics. The only way to get this to work would be to take a Class argument, so the method knows what type of object to create. It can't know at the moment, because of Type Erasure.
Alternatively (much simpler) is to always return DateTime and do away with generics here.
The client will always know what it wants, and if the client wants a Date, it can create one from the DateTime far more easily than what you are trying to do.
Example:
Client 1 wants a DateTime:
DateTime result = service.convertTimeForServer(dt);
Client 2 wants a Date:
Date result = service.convertTimeForServer(dt).toDate();

convert object into date

I get an ArrayList of Object[] from a database and I want to convert the java.sql.Date stored in an object into a java.util.Date (in order to use it in jfreechart):
my code is as follows:
fills up the Array of object with data from MySQL
ArrayList<Object[]> mydata=new ArrayList<>();
mydata=sqlGetter.getMdbObjectList(sqlString, null);
for(Object[] myobject : mydata){
if (myobject[1].getClass()==java.sql.Date.class){
java.util.Date mydate=null;
mydate = Date ( myobject[1]);
}
}
Netbeans return an error: "Java incompatible types: Object cannot be converted to Date"
While I understand the idea, I would have expected to be able to cast the object into a Date after having checked that it is indeed of the right class.
I'm starting java, so please any helps on the obvious mistake that I must be doing would be useful.
You are missing a cast. Additionally, you'd be better off using the instanceof operator:
for(Object[] myobject : mydata){
// Note that java.sql.Date extends java.util.Date
if (myobject[1] instanceof java.util.Date) {
java.util.Date mydate = (java.util.Date) myobject[1];
}
}
you just need to explicit cast the object to Date
ex: (Date) obj;

get() method behavior in ArrayList() having raw type but no type parameter

I am working over Java collections.
I found something strange and not getting why is this happening.
So here is the scenario.
ArrayList al = new ArrayList();
al.add("Hello World");
//The below line is creating some confusion
System.out.print(al.get(0));
Now the last line is printing "Hello World" as it is.
But as i am not using any type parameter it should give an object type in return.So it should call the Object's toString() instead of String's toString().
Does it depend on the object type which is getting saved (like String here ) of the return type (like Object).
Please help.
Actually all the trick is not related to generics even you snippet showcase it.
It related to overriden methods, toString() is defined in the super super class Object and overriden in the String class, that are evalutated at runtime using the actual object type and not its reference, i.e when calling:
Object o = new String("hello");
o.toString(); // Here at runtime, the JVM will call the "hello" toString method and not the Object one.
In you code, you have called:
al.add("Hello World");
The above line do the following:
Creates a new String object with Hello World as a literal and add it to the string pool.
Makes the first element in the list (element at index 0) reference that object (that is a String one).
Now when calling System.out.print(al.get(0));:
The first element of the list, which is an Object reference to a String object, got his toString() method called and which as already said will evalute to the object real type and not the refence type, i.e. you will have String#toString method called.
If you want to return Strings from a collection you'll have to initialise it like this, using a String type parameter:
ArrayList<String> al = new ArrayList<String>();
// ^^^^^^^^ ^^^^^^^^
al.add("Hello World");
String value = al.get(0); //<-- now you can get Strings
Now, however you will only be able to get objects, and you will have to cast before getting back to your original type:
ArrayList al = new ArrayList();
al.add("Hello World");
Object object = al.get(0); //<-- ok
String value = (String)al.get(0); // <-- ok
value = al.get(0); //<-- wont compile
Edit
ArrayList al = new ArrayList();
al.add("Hello World");
Object object = al.get(0); //<-- ok
String value = object.toString();
In this case, calling object.toString(), will just return the object as a String. It will call the toString method on the String class, which just returns itself.
When calling a method of an object, the actual method that is called is of the actual type of the object. This is why the toString that is actually called is the String class method.
BTW: generic types are for compile-time, and not for runtime. For example you can't have in the same class 2 methods like:
void foo(List l) and
void foo(List l) since after compiling both have the same signature.

In Java how should I compare an object to a const value?

I've created my own MyDate class. It basically wraps a Long value with some pretty toString() functions. I've implemented equals() and compareTo(). my program reads some data and instantiates object of classes that hold this MyDate class. Problem is that sometimes that data is bad so I created a public static final long NODATE = Long.MIN_VALUE; so that I could initiate a new instance that is empty (replace the null in the containing class so to avoid NullPointerExceptions). I've also implemented a constructor with no arguments that inits the Long value to NODATE.
My Problem:
I want to check if a MyDate is valued as NODATE. I can't compare to NODATE since it's Long and not MyDate. One way to do this is:
if someObject.myDate.equals(new MyDate()).
But it seems like a waste to create an object just to make the comparison? Another way is to implement MyDate.amINoDate() method.
Is there another way? I was thinking of creating an static instance of MyDate that is inited to NODATE and to compare to it. But how can I compare my non static objects to this static object?
class MyDate {
public static final MyDate NODATE = new MyDate(Long.MIN_VALUE);
// ...
}
// ...
if (someDate.equals(MyDate.NODATE)) // ...
Thanks maskacovnik.
You can also add a method to MyDate like:
public boolean isNodate() {
return internalLongDate == Long.MIN_VALUE;
}
Add a method to MyDate:
if (someDate.isNoDate()) {
...
}
Also: personally I would avoid the Long.MIN_VALUE and use null.

Cannot cast from int to MyClass

I have a problem in dealing with the conversion of integer to string. This is my code :
MyClass getRow;
getRow = (MyClass) getListAdapter().getCount();
I found an error on this line: Cannot cast from int to MyClass
This is my MyClass ListView Adapter :
public String toString() {
return myclass;
}
Solved
I have found a solution by adding a few tricks to convert an integer to a string, like this :
int i ;
i = getListAdapter().getCount();
String str = String.valueOf(i);
TextView totalRow = (TextView) findViewById(R.id.totalRow);
totalRow.setText(str);
thanks for all of your answers, awesome Stackoverflow !
int is a primitive and not a class, so the compiler is correct. Why do you expect that an int transform magically into MyClass? What are you trying to do here?
If I understand you correct, you must assing the value of getRow() to your class somehow (either via a setter, by constructor or by accessing the member) and then you can use MyClass. Of course if you want to convert the int to a String object, you have to convert it:
String s = String.valueof(integervalue);
You cannot cast an int to an Object. In the first row you mention you are exactly doing that. getCount() returns an int and you try to cast it to (MyClass).
You never cast primitives to objects in java.
No, you cannot cast this. However, you can achieve a similar effect if you create a constructor for MyClass which accepts an integer as input. So something like:
public MyClass(int x) {
// do stuff to convert as you see fit here
}
then when using it, you do:
getRow = new MyClass( getListAdapter().getCount());

Categories