theGrayFox theGrayFox - 10 days ago 7
Java Question

Java: Verify Class Exists

I thought this would be a trivial matter, but I can't seem to find a method similar to

class_exists
in Java. I'm writing a test to verify that a class name is defined. How can I replicate this in Java with jUnit?

<?php

$this->assertTrue(class_exists('Car'), 'Should have a class called "Car"');


TestCar.java

import org.junit.Assert;

import org.junit.Test;

public class TestCar {

@Test
public void testCarExists() {
try {
Class.forName("Car");
} catch(ClassNotFoundException e) {
Assert.fail("Should create a class called 'Car'.");
}
}
}


Car.java

public class Car {
// just enough :-)
}

Answer

One advantage of Java is that you have a compiler, so usually this is a non-issue. If you compile your code properly and then, for some reason, drop a required jar file from the runtime environment, you'll get a java.lang.ClassNotFoundException, so that should be enough.

If you want to be super-extra-safe, you could try calling Class.forName:

@Test
public void testClassExists {
    try {
        Class.forName("org.mypackage.Car");
    } catch (ClassNotFoundException e) {
        Assert.fail("should have a class called Car");
    }
}
Comments