I want to create an object of child class
more than 100 class extend MasterClass
MasterClass is
public class MasterClass{
int key;
String value;
String displayValue;
boolean status;
}
public class User extends MasterClass{
public User(){ }
}
public class Customer extends MasterClass{
String productName;
public Customer (){ }
}
etc...
i will get a MasterClass object from client, i wanted to type cast that object to respective one
if(masterClass instanceof User) {
User a_user = (User) a_ masterClass;
…
} else if(masterClass instanceof Customer) {
Customer a_customer = (Customer) a_ masterClass;
…
}
if i do this i will end up with 100s of else if.
Please let me know how i can achieve this without else if?
Thanks in advance.
Use polymorphism and generics, as Java intended.
Polymorphism lets you call a method on your object that behaves differently for every type. The easiest way to achieve this is to provide an abstract method in the base class MasterClass and then override it with different functionality in every extended class. You are probably looking for something like this:
class MasterClass {
int age;
// ...
public abstract void doWork();
public int getAge() { return age; }
// .. more methods
}
class User extends MasterClass {
// customize User here
#Override
public void doWork() { /* User does work in some way */ }
}
class Customer extends MasterClass {
// customize Customer here
#Override
public void doWork() { /* Customer does work in some other way */ }
}
// ...
If you are not too familiar with OOP, here is a good introductory tutorial.
If you are not allowed to alter your classes, you can populate a look-up table like HashMap<Class, MyFunctor> where you can assign a different functor for every type of person you have.
Also, you might want to use generics. Generics allow you to capture and restrict the type of objects passed to your methods.
Maybe you can use generics with the constraint T extends MasterClass?
Using basic concepts of Design Pattern you can create a constructor like this in the object where you try to initialize
MasterClass masterClass;
public MyCreatorOject(MasterClass masterClass)
{
this.masterClass = masterClass;
}
later when you create the object it can be
new MyCreatorObject(new User());
or
new MyCreatorObject(new Customer());
Related
Firstly, I believe my question is badly worded but don't really understand how to phrase it.
I have a starting interface that is being implemented by a number of classes. What I want to do is to see if there is a way to create a new object such that I am being passed the generic interface, then based on the method .getClass().getSimpleName(), create a new object based on that string.
Is the only way to create a switch case statement? As the number of implementing classes are too many (about 100 or so).
Reference code:
public interface MyInterface {
public void someMethod();
}
then I would have my implementing classes:
public class MyClass1 implements MyInterface {
public void someMethod() { //statements }
}
public class MyClass2 implements MyInterface {
public void someMethod() { //statements }
}
public class MyClass3 implements MyInterface {
public void someMethod() { //statements }
}
What I want to have in the end is another class which is passed an argument of type MyInterface, get the simple name from that and create a new instance of MyClassX based on that simple name.
public class AnotherClass {
public void someMethod(MyInterface interface) {
if (interface == null) {
System.err.println("Invalid reference!");
System.exit(-1);
} else {
String interfaceName = interface.getClass().getSimpleName();
/**
* This is where my problem is!
*/
MyInterface newInterface = new <interfaceName> // where interfaceName would be MyClass1 or 2 or 3...
}
}
}
Any help is highly appreciated!
You can use reflection for this:
public void someMethod(MyInterface myInterface) {
Class<MyInterface> cl = myInterface.getClass();
MyInteface realImplementationObject = cl.newInstance(); // handle exceptions in try/catch block
}
This is a common problem with many solutions. When I face it, I never use reflection because it is difficult to maintain if it is part of a big project.
Typically this problem comes when you have to build an object based on a user selection. You can try a Decorator pattern for that. So, instead of building a different object for each option. You can build a single object adding functionality depending on a selection. For instance:
// you have
Pizza defaultPizza = new BoringPizza();
// user add some ingredients
Pizza commonPizza = new WithCheese(defaultPizza);
// more interesting pizza
Pizza myFavorite = new WithMushroom(commonPizza);
// and so on ...
// then, when the user checks the ingredients, he will see what he ordered:
pizza.ingredients();
// this should show cheese, mushroom, etc.
under the hood:
class WithMushroom implements Pizza {
private final Pizza decorated;
public WithMushroom(Pizza decorated) {
this.decorated = decorated;
}
#Override
public Lizt<String> ingredients() {
List<String> pizzaIngredients = this.decorated.ingredients();
// add the new ingredient
pizzaIngredients.add("Mushroom");
// return the ingredients with the new one
return pizzaIngredients;
}
}
The point is that you are not creating an object for each option. Instead, you create a single object with the required functionality. And each decorator encapsulates a single functionality.
I have classes Productand ProductImage
I want them both to have the following set of booleans: toBeSynced, toBeAdded and toBeDeleted
How can I enforce that using some OOP Design pattern? I thought of interfaces but those are for meethods. I dont want them to extend a Syncable class because it doesnt feel right. I dont want to manually add those booleans to both classes, I want the booleans to come from somewhere else.
EDIT: I understood that this can be achieved by annotations. How would that work?
You may use composition if you want:
class Sync {
boolean toBeSynced, toBeAdded ,toBeDeleted
}
class Product {
Sync sync;
}
class ProductImage {
Sync sync;
}
You can use composition to "mixin" the values that you want.
For example, we can have a class called Syncable, which has the values you want.
public class Syncable
{
// instance variables - replace the example below with your own
private boolean toBeSynced;
public void setToBeSynced(boolean toBeSynced){
this.toBeSynced = toBeSynced;
}
public boolean getToBeSynced(){
return this.toBeSynced;
}
}
Then, in your product class for example
public class Product
{
Syncable sync;
public Product()
{
sync = new Syncable();
}
}
After doing this, you can modify the boolean values as you wish.
public static void main(String[] args){
Product p = new Product();
p.sync.setToBeSynced(false);
System.out.println(p.sync.getToBeSynced());
}
Of course, you may wish to add another layer of abstraction with methods in the product class that can set and get the boolean values that you want.
For example, you could add the following 2 methods to the product class:
public void setBoolean(boolean bool){
this.sync.setToBeSynced(bool);
}
public boolean getBoolean(){
return this.sync.getToBeSynced();
}
Then, in another part of your program, you could state
Product p = new Product();
p.setBoolean(true);
boolean bool = p.getBoolean();
The best way is through inheritance, by using an abstract class to define the common properties.
if it does not feel right, your naming and/or design is probably incorrect
abstract class Syncable {
boolean toBeSynced;
boolean toBeAdded;
boolean toBeDeleted;
abstract void sync();
abstract void add();
abstract void delete();
}
Product:
class Product extends Syncable {
// impl...
}
ProductImage:
class ProductImage extends Syncable {
// impl...
}
EDIT:
You should really think about what your classes are going to do, i.e is-a (inheritance) vs has-a (composition) relationships, for example:
is a Product a Syncable versus does a Product have a Sync object;
in the same way you would think of a Car, does a car have wheels, or is it a wheel? i think not ;)
I am looking for a good way to have different implementations of the same method which is defined in an interface but with different parameter types. Would this be possible?
In order to clarify this, suppose I have an interface Database and two implementing classes Database1 and Database2. Database has a method createNode(...) and another one modifyNode(...). The problem is that for Database1 the return type of the createNode method should be a long (the identifier). For Database2, however, it would be an object specific from the technology (in this case OrientDB but this doesn't matter too much, it is simply something that extends Object, of course). And also both create(...) return types should be used as one of modifyNode(...) parameters.
What I was thinking to do is:
`public interface Database {
public Object createNode(...);
public void modifyNode(Object id, ...);
...
}`
public class Database1 {
#Override
public Object createNode(...) {
...
long result = // obtain id of created node
return Long.valueOf(result);
}
#Override
public void modifyNode(Object id, ...) {
...
// use id as ((Long)id).longValue();
}
}
public class Database2 {
#Override
public Object createNode(...) {
...
SomeObject result = // obtain id of created node
return result;
}
#Override
public void modifyNode(Object id, ...) {
...
// use id as (SomeObject)id
}
}
I wanted to know if there is a better way to do this. Specially to avoid Long -> long and long -> Long conversions. I saw many similar questions here in StackOverflow but none of them were what I was looking for. Thank you very much in advance.
Here's an example of Generics
Database
public interface Database<T> {
public T createNode(...);
public void modifyNode(T id, ...);
...
}
Database1
class Database1 implements Database<Long> {
#Override
public Long createNode(...) {
...
long result = // obtain id of created node
return result;
}
#Override
public void modifyNode(Long id, ...) {
...
// use id
}
}
Database2
public class Database2 implements Database<SomeObject> {
#Override
public SomeObject createNode(...) {
...
SomeObject result = // obtain id of created node
return result;
}
#Override
public void modifyNode(SomeObject id, ...) {
...
// use id as (SomeObject)id
}
}
Btw, don't worry about autoboxing. You are using JDK >= 5 since there are #Override annotations.
I think you want Generic Methods.
Generic methods are methods that introduce their own type parameters.
This is similar to declaring a generic type, but the type parameter's
scope is limited to the method where it is declared. Static and
non-static generic methods are allowed, as well as generic class
constructors.
The syntax for a generic method includes a type parameter, inside
angle brackets, and appears before the method's return type. For
static generic methods, the type parameter section must appear before
the method's return type.
I have an enum
public enum Vehicle {
CAR("CAR", "Car"), PUSHBIKE("PUSHBIKE", "PuschBike");
public boolean isCar()
{
...
}
public boolean isPushBike()
{
....
}
}
I have a 2 DAO CarDAO and PushBikeDAO which is are implementing a BaseDao
I have a JSF managed bean somthing like this
public class JsfManagedBean {
private Vehicle vehicle;
private BaseDAO baseDao;
public void Search()
{
//I need to get rid of this if statement
if (vehicle.isCar())
{
baseDao = new CarDao;
baseDao.search();
}
else if(vehicle.isPushBike())
{
baseDao = new PushBike;
baseDao.search();
}
//Please Note each type of search is very different call to an other party's Jar
}
}
I am trying to get rid of this if statement possibly by using generics or any proper OO technique
may be something like
baseDao = new baseDaoImpl<getClass(vehicle.getcode())>
where if vehicle.getcode() returns String value Car I do have a model class Car.
Just loud thinking (clinching the straws really :)).
This is an offshot of this question of mine
Add a method to the enum that calls new and returns the right dao.
Let each of the enum constants define their respective DAO classes:
public enum Vehicle {
CAR("CAR", "Car"){
public BaseDAO getNewDAO(){
return new CarDAO();
}
},
PUSHBIKE("PUSHBIKE", "PuschBike"){
public BaseDAO getNewDAO() {
return new PushBikeDAO();
}
};
Vehicle(String a, String b){/* ... */}
//this forces every enum constant to implement a getNewDAO() method:
abstract BaseDAO getNewDAO();
}
This way, you can use:
public void Search() {
baseDao = vehicle.getNewDAO();
baseDao.search();
}
Take a look at the Factory method pattern and the Strategy pattern if you'd like to know more. Enums are my preferred way to use the latter.
I would use a factory method, like so:
public class JsfManagedBean {
private static final Map<Vehicle,BaseDAO> daos;
static {
Map<Vehicle,BaseDAO> tmp = new HashMap<Vehicle,BaseDAO>();
tmp.put(Vehicle.CAR,new CarDAO());
tmp.put(Vehicle.BIKE,new BikeDAO());
daos = Collections.unmodifiableMap(tmp);
}
public static getDao(Vehicle v) {
return daos.get(v);
}
private Vehicle vehicle;
private BaseDAO baseDao;
public void Search()
{
baseDao = getDao(vehicle);
baseDao.search();
}
}
Unless you have more uses for DAO objects, you could make this code shorter:
if (vehicle.isCar()) new CarDao().search();
else if(vehicle.isPushBike()) new PushbikeDao().search();
With two alternatives, I'd stay with the if statement. If you had really many variants of vehicles, you could use a hash table keyed by the enum values and storing the DAO classes:
Map<Vehicle, Class> DAOClass = new HashMap<...>();
...
DAOClass.get(vehicle).getConstructor().newInstance().search();
Reflection is not that slow not to use here.
I have a design problem.
I have two data objects which are instances of say class A and class B.
A and B don't have any behavior - they are java beans with getters and setters.
I have a Validation interface and 10 implementations of it defining different Validations.
I would like to specify in my properties file which Validation applies to which class.
Something like this:
class A XYZValidation,ABCValidation
class B: ABCValidation, PPPValidation, etc
How do I write my Validation class so that it serves objects that are instances of Class A OR ClassB, or just about any other Class C that I might want to add in future?
interface Validation {
public boolean check(??);
}
> Just wanted to add this line to say thank you to all those who have responded to this post and to say that I am loving my time here on this amazing website. Stackoverflow rocks!
Have you thought about using annotations to mark the fields you want to validate in your bean?
If you have 10 different validations you could specify 10 annotations. Then mark the fields using annotations:
#ValideStringIsCapitalCase
private String myString;
#ValidateIsNegative
private int myInt;
With reflection API iterate through all the fields and see if they are marked, something like this:
public static <T> validateBean(T myBean) throws IllegalAccessException {
Field[] fields = myBean.getClass().getDeclaredFields();
// This does not take fields of superclass into account
if (fields != null) {
for (Field field : allFields) {
if (field.isAnnotationPresent(ValideStringIsCapitalCase.class)) {
field.setAccessible(true);
Object value = field.get(existingEntity);
// Validate
field.setAccessible(false);
}
}
}
}
An option would be to mark the whole class with the validator you want to use.
EDIT: remember to include annotation:
#Retention(RetentionPolicy.RUNTIME)
for your annotation interface.
EDIT2: please don't modify the fields directly (as in the example above). Instead access their getters and setters using reflection.
I've probably misunderstood the question but would something like this suffice:
public class ValidationMappings {
private Map<Class, Class<Validation>[]> mappings = new HashMap<Class, Class<Validation>[]>();
public ValidationMappings() {
mappings.put(A.class, new Class[]{XYZValidation.class, ABCValidation.class});
mappings.put(B.class, new Class[]{ABCValidation.class, PPPValidation.class});
}
public Class[] getValidators(Class cls) {
if (!mappings.containsKey(cls)) return new Class[]{};
return mappings.get(cls);
}
}
When you want to get the list of validators for a particular class, you would then call getValidators(Class cls) and iterate over each validator and create an instance of each and call your check method.
something like this maybe?
interface Validation {
public boolean check(Validatable x);
}
interface Validatable {
}
class A implements Validatable {
...
}
class Validator {
public boolean validateObject(Validatable x){
boolean validated = true;
... //read config file, check which validation classes to call
//for each validation class v in the config file:
if(!v.check(x)) validated = false;
return validated;
}
}
If you just want it to deal with any object then it'll be Object's that your interface
public boolean check(Object o);
Unless you want to use some marker interface to tag classes that are suitable for validation
Did you mean:
public interface Validation<T> {
boolean check(T object)
}
First of all, I'd use the following interface
interface Validator {
boolean isValid(Object object);
}
to implicitly document what the return value actually means.
Secondly, I'd suggest to document in the interface what behavior is expected if the Validator doesn't know how to handle the given instance.
interface Validator {
/**
* #return false if this validator detects that the given instance is invalid, true if the given object is valid or this Validator can't validate it.
*/
boolean isValid(Object object);
}
That way, you'd simply have a List of Validators that you could throw your objects at.
The performance impact of incompatible Validators should be negligible if they are implemented properly, e.g. with an early instanceof.
On a side note, I'd use a List of Validators instead of a Set so you can order them according to complexity. Put the cheap (performance-wise) Validators at the start of the List as an optimization.
You could then use a general piece of code for validation, e.g.
public class Validators {
public static boolean isValid(Object o, Collection<Validator> validators) {
for(Validator current : validators) {
if(!current.isValid()) return false;
}
return true;
}
}
Depending on your use-case it might be a good idea to return something different than boolean in your interface. If you need information about what is wrong, e.g. to display it, you'd need to return that info instead.
In that case it might be a good idea to keep the above loop running so you'll get all validation errors instead of only the first.
A Visitor pattern would solve this
Calling the Visitor Validator it's possible to have this:
public interface Validatable {
public boolean validate(Validator v);
}
public interface Validator {
public boolean validate(A a);
public boolean validate(B b);
}
public class A implements Validatable {
public boolean validate(Validator v){
return v.validate(this);
}
}
public class B implements Validatable {
public void validate(Validator v) {
return v.validate(this);
}
}
// Default validator just doesn't know how to
// validate neither A's, nor B's
public class GenericValidator implements Validator {
public boolean validate(A a) {
throw new UnsupportedOperationException("Cannot validate A");
}
public boolean validate(B b) {
throw new UnsupportedOperationException("Cannot validate B");
}
}
// since XYZValidation is supposed to run only on A's
// it only overrides A validation
public class XYZValidation extends GenericValidator {
public boolean validate(A a) {
// validate a
return isVAlid(a);
}
}
// since ABCValidation is supposed to run on A's and B's
// it overrides A and B validation
public class ABCValidation extends GenericValidator {
public boolean validate(A a) {
// validate a
return isVAlid(a);
}
public boolean validate(B b) {
// validate b
return isVAlid(b);
}
}
// since ABCValidation is supposed to run only on B's
// it overrides A only B validation
public class PPPValidation extends GenericValidator {
public boolean validate(B b) {
// validate b
return isVAlid(b);
}
}