Tag Archives: java

Dynamic Type Selection in PHP

So, check out this block of PHP code:

class MyClass {
  public function doSomething() {
    echo "Hello there.";
  }
}
$class = "MyClass";
$method = "doSomething";
$instance = new $class();
$instance->$method();

The “new” statement is using a string variable to specify the class being instantiated! What’s more, on the very next line, another string variable is being used, this time to specify the method being invoked.

My background is C-like languages (C, C++, C# and Java), so I was somewhat surprised to discover that this not only executes, but does so without errors. Turns out, this is just how PHP’s new statement works.

In Java, you’d use Class<T> to get the class object, retrieve a specific constructor, and then call the newInstance method, passing any required parameters. So the above example would end up looking something like this:

package myprogram;

import java.lang.Class;
import java.lang.reflect.Method;

class MyClass {
    public MyClass() {}
    public void doSomething() {
        System.out.println("Hello there.");
    }

    public static void main(String[] args) {
        String className = "myprogram.MyClass";
        Class<?> class = Class.forName(className);
        MyClass instance = class.getConstructor().newInstance();

        Method method = class.getMethod("doSomething");
        method.invoke(instance);
    }
}

In a more complex code sample (e.g. passing arbitrary class objects into a method to be instantiated and used in a callback), the Java version has definite advantages in terms of compile time type checking.

But I can’t deny that the simplicity of the PHP version also has some appeal.

What is an SDK vs. a JDK vs. a JRE?

The Content Management System we use at the office is written in Java, so on the development systems, we need to be careful to match the JDK version to the JRE version used by the CMS vendor. Periodically someone new will join the team, and they end up wondering what a JDK is and how is that different from a JRE?

So let’s break this down. Generally speaking, an SDK or Software Development Kit. Basically, it’s the set of compilers, debuggers, and other tools used for creating software on a given platform.

That’s basically what the JDK is.  The Java Development Kit contains compilers, debuggers and other tools for creating Java applications.

While a software (or Java) development kit allows you to create software, some software platforms also require a runtime environment. The JRE, or Java Runtime Environment is the support software that allows a Java application to execute.

(Photo from Pexels.com, used under Creative Commons Zero.)