views:

1550

answers:

3
Class someInterface = Class.fromName("some.package.SomeInterface");

How do I now create a new class that implements someInterface?

I need to create a new class, and pass it to a function that needs a SomeInterface as an argument.

+11  A: 

Creating something which pretends to implement an interface on the fly actually isn't too hard. You can use java.lang.reflect.Proxy after implementing InvocationHandler to handle any method calls.

Of course, you could actually generate a real class with a library like BCEL.

If this is for test purposes, you should look at mocking frameworks like jMock and EasyMock.

Jon Skeet
Whoa, neat! I wonder what else is in the java.lang.reflect package that I don't know about?
Michael Myers
That's really cool, thanks!
Isaac Waller
+1  A: 

If you want to go beyond interfaces, you might want to take a look at cglib and objenesis. Together, they will allow you to do some pretty powerful stuff, extending an abstract class and instantiating it. (jMock uses them for that purpose, for example.)

If you want to stick with interfaces, do what Jon Skeet said :).

jqno
A: 

Actually, you have to use the class name in Class.fromName() method and cast to your interface type. See if the sample below helps.

public class Main {

    public static void main(String[] args) throws Exception {
     Car ferrari = (Car) Class.forName("Mercedez").newInstance();
     System.out.println(ferrari.getName());
    }
}

interface Car {
    String getName();
}

class Mercedez implements Car {

    @Override
    public String getName() {
     return "Mercedez";
    }

}

class Ferrari implements Car {

    @Override
    public String getName() {
     return "Ferrari";
    }

}
nandokakimoto