Email templates: sptools.getClass behaviour

I have the following lines at the top of an email template (testing out a strange behaviour I’m seeing):

#set($sdf = $spTools.getClass().forName("java.text.SimpleDateFormat").getInstance()) $sdf.getClass().getName()
#set($tz = $spTools.getClass().forName("java.util.TimeZone").getInstance()) $tz.getClass().getName()
#set($cal = $spTools.getClass().forName("java.util.Calendar").getInstance())$cal.getClass().getName()

But all that’s running is this (three times, identical):

java.text.SimpleDateFormat
java.text.SimpleDateFormat
java.text.SimpleDateFormat

Why is this happening?

getInstance() in Java does not necessarily return an instance of the base class. It often returns a subclass.

What your code does:

#set($sdf = $spTools.getClass().forName(“java.text.SimpleDateFormat”).getInstance())
$sdf.getClass().getName()
This is trying to create an instance of SimpleDateFormat via Class.forName().getInstance()
Then you’re printing out the class name to see what it actually created.

#set($tz = $spTools.getClass().forName(“java.util.TimeZone”).getInstance())
$tz.getClass().getName()

Same idea for TimeZone.

#set($cal = $spTools.getClass().forName(“java.util.Calendar”).getInstance())
$cal.getClass().getName()

And again for Calendar.

getInstance() in Java does not necessarily return an instance of the base class. It often returns a subclass.
For example:

java.text.SimpleDateFormat.getInstance() → returns a pre-configured SimpleDateFormat object.

java.util.Calendar.getInstance() → returns an instance of GregorianCalendar.

java.util.TimeZone.getInstance() → returns the system’s default TimeZone, usually a subclass like sun.util.calendar.ZoneInfo (in Oracle JDK).

If you’re testing behavior:

$sdf.format($cal.time)
$tz.getID()
set specific formats/time zones to test behavior changes:

#set($sdf = $spTools.getClass().forName(“java.text.SimpleDateFormat”).newInstance())
$sdf.applyPattern(“yyyy-MM-dd HH:mm:ss”)
$sdf.format($cal.time)

Why the behavior might be strange:
getInstance() in Java does not necessarily return an instance of the base class. It often returns a subclass.
For example:

java.text.SimpleDateFormat.getInstance() → returns a pre-configured SimpleDateFormat object.

java.util.Calendar.getInstance() → returns an instance of GregorianCalendar.

java.util.TimeZone.getInstance() → returns the system’s default TimeZone, usually a subclass like sun.util.calendar.ZoneInfo (in Oracle JDK).

That doesn’t seem to explain why java.text.SimpleDateFormat is returned for all three of them.