Creating anonymous dynamic runtime instances

How can I create implementations of an interface dynamically at runtime in java?

I have a factory that will read the annotations on class Foo and create an instance of class Bar. For this factory to be type safe, I'd like my client factories to be interfaces with a factory method that takes type Foo and returns type Bar. I then want my factory to implement this factory method at runtime.

All of this is because the factory code would be redundant and hard to maintain. If generated at runtime, it would always be current.

Example:

public class Foo{
    private String name;

    public String getName(){
        return name;
    }

    public void setName(String name){
        this.name = name;
    }
}

public class Bar{
    private String personName;

    public String getPersonName(){
        return personName;
    }

    public void setPersonName(String personName){
        this.personName= personName;
    }
}

public interface BarFactory{
    Bar create(Foo foo);
}

Is there a way to do this?

Answer:1

Use Java Proxy reflection. See examples here: http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html

Answer:2

if you want to just to create some instance that implement desired interface - you can simply do something like this:

public <T> T newInstance (Class<T> type) {
    try {
        return type.newInstance();
    } catch (Exception ex) {
        try {
            // Try a private constructor.
            Constructor<T> constructor = type.getDeclaredConstructor();
            constructor.setAccessible(true);
            return constructor.newInstance();
        } catch (SecurityException ignored) {
        } catch (NoSuchMethodException ignored) {
            if (type.isMemberClass() && !Modifier.isStatic(type.getModifiers()))
                throw new SerializationException("Class cannot be created (non-static member class): " + type.getName(), ex);
            else
                throw new SerializationException("Class cannot be created (missing no-arg constructor): " + type.getName(), ex);
        } catch (Exception privateConstructorException) {
            ex = privateConstructorException;
        }
        throw new SerializationException("Error constructing instance of class: " + type.getName(), ex);
    }
}

If you need to create a fully dynamic implementation of inteface then you need to use Proxy class http://www.javaworld.com/javaworld/jw-11-2000/jw-1110-proxy.html

Is this something you are looking for?

Answer:3

I'm trying to understand recursion with the help of few examples. I found this example of printing all possible combinations of r elements in a given array of size n using recursion. Print all ...

I need to create some directories and files and all of them should have permission 0600. When I Run from NetBeans Debug: After creating directory when i try to store some files there I get IOException ...

I am writing a program which reads in files and then processes them. At the moment, I am using a BufferedReader to read in a list of files from a txt file. This txt file was generated in a command ...

Question about ScheduledExecutorService.shceduleAtFixedRate - I schedule taskA to run every 500 millis, which blocks for 1000 millis. Now subsequent executions aren't gonna wait the extra 500 millis, ...