Passing class name as parameter

Using reflection it is possible. Here for a given className (passed as a string) . This class will be searched in memory ( it should be already loaded).

The name of the class to be instantiated when passed as a string should be fully qualified

void createInstanceOfClass(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException{


        Class classTemp = Class.forName(className);

        Object obj =classTemp.newInstance();



    }
}

Why not use a factory pattern approach.

public interface Alert {}

public class RedAlert implements Alert {}
public class YellowAlert implements Alert {}
public class BlueAlert implements Alert {}

public interface AlertFactory {
    Alert create();
}

public class RedAlertFactory implements AlertFactory {
    public Alert create() {
        return new RedAlert();
    }
}

public class YellowAlertFactory implements AlertFactory {
    public Alert create() {
        return new YellowAlert();
    }
}

public class BlueAlertFactory implements AlertFactory {
    public Alert create() {
        return new BlueAlert();
    }
}

// your setAlert method could probably look like this
public void setAlert(AlertFactory factory) {
    aInstance = factory->create();
}

Then you could do something like this.

setAlert(new RedAlertFactory()); // or YellowAlertFactory, BlueAlertFactory

It's possible to use your approach using java.lang.Class#newInstance.


Instead of passing the class name, you can pass the class itself and use reflection to create a new instance of the class. Here's a basic example (assuming all your XxxAlert classes extend from an Alert class):

public <T extends Alert> void setAlert(Class<T> clazzAlert) {
    Alert alert = clazzAlert.newInstance();
    //use the alert object as you want/need...
}

Now you just call the method like this:

setAlert(RedAlert.class);

Note that it would be better using a super class in T parameter, otherwise you (or another programmer) could do this:

setAlert(Object.class);

which would be plain wrong.

Tags:

Java