Question

I am creating a class in Delphi that will call methods in a Java class;

I had no problems with primitives/wrappers or String types, but I'm having problems with Date.

In java I have a setDateStart(java.util.Date dateStart) method, how can I call it in Delphi?

procedure TMyJavaObject.SetDateStart(const DateStart: TDateTime);
var
    method : JMethodID;
begin
    method := getMethod(self.clazz, 'setDateStart', '(Ljava/util/Date;)V');
    JNIEnv.CallVoidMethod(self.javaObject, method, [DateStart]);
end;
Was it helpful?

Solution

Ljava/uitl/Date is misspelled. Should be Ljava/util/Date instead.

Also, a Delphi TDateTime, which is implemented as a Double, is not compatible with a Java java.util.Date, which is an object instance. You need to create a real Date object instance and assign the TDateTime value to it as needed.

Try something more like this instead (I don't use JNI in Delphi, so this might need some tweaking, but you get the idea):

uses
    ..., DateUtils;

procedure TMyJavaObject.SetDateStart(const DateStart: TDateTime);
var
  DateValue: Int64; // a Java 'long' is a 64-bit type
  DateClass: JClass;
  DateObj: JObject;
  method : JMethodID;
begin
  // DateTimeToUnix() returns a value in seconds,
  // but the java.util.Date(long) constructor expects
  // a value in milliseconds instead...
  DateValue := DateTimeToUnix(DateStart) * 1000;

  // create a java.util.Date object instance, passing the
  // converted TDateTime value as a 'long' to its constructor...
  DateClass := JNIEnv.FindClass('java/util/Date');
  method := JNIEnv.GetMethodID(DateClass, '<init>', '(J)V');
  DateObj := JNIEnv.NewObject(DateClass, method, [DateValue]);

  // pass the java.util.Date object to the desired object method...
  method := getMethod(self.clazz, 'setDateStart', '(Ljava/util/Date;)V');
  JNIEnv.CallVoidMethod(self.javaObject, method, [DateObj]);
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top