Strategy pattern, pass function into parent method - java

I would like to implement something like Strategy Pattern. I have generalized logic in Parent method, I need to pass specific logic (with casting etc..) into parent.
I have following classes:
class A{
public Object generateData(Function fetchData, AbstractForm form)
{
List<DataBean> dataBeans = (List<DataBean>) fetchData.apply(form);
//...
}
}
class B extends A{
void someMethod(AbstractForm form){
Function<AbstractForm, List<DataBean>> fetchFunction = new Function<AbstractForm, List<DataBean>>() {
//here goes form specific casting and other data fetch specific logic
return dataBeans;
}
super.generateData(fetchFunction, form);
}
}
Did I get the Idea of function correctly here?

Correct use of the Strategy pattern implies aggregation between a Context (in your case class A) and a Strategy (in your case an implementation of Function).
You can see the relationship in the image below (taken from the Gang of Four book, Design patterns: elements of reusable object-oriented software).
Below I've applied a traditional Strategy pattern approach to your problem. In this case I've made it so that Function.apply(AbstractForm) returns List<DataBean> to remove the need for casting. You could of course use generics to make Function more flexible.
Strategy
public interface Function {
List<DataBean> apply(AbstractForm form);
}
Context
public class A {
private Function fetchData; // strategy
public void setStrategy(Function fetchData) { // method for setting the strategy
this.fetchData = fetchData;
}
// precondition: fetchData != null
public Object generateData(AbstractForm form) {
List<DataBean> dataBeans = fetchData.apply(form); // using the strategy
return null; // whatever you want to return
}
}
In this case, extending class A is not neccessary as we can inject our Strategy (Function) using setStrategy(Function). However, we could always extend A to great an object with a predefined Strategy.
For example:
public class B extends A {
public B() {
setStrategy((form) -> null); // implement your concrete strategy here
}
}
Using a Factory Method
Since a Strategy for fetching the data is likely required and there may be no 'default' to use and may not ever change, the Factory method pattern could be used instead to enforce the creation of a Product (Function). Note class A is now abstract and includes a Factory method createFunction() which is then implemented in the subclasses (e.g. B) to create the Function.
The design for the factory method pattern can be seen in the UML below. In this case our Product is now what was previously our Strategy (Function) and the Creator is class A, with the ConcreteCreator being class B.
Creator
public abstract class A {
private Function fetchData; // product to be used
public class A() {
fetchData = createFunction(); // call factory method
}
protected abstract Function createFunction(); // factory method
// precondition: fetchData != null
public Object generateData(AbstractForm form) {
List<DataBean> dataBeans = fetchData.apply(form); // using the product
return null; // whatever you want to return
}
}
ConcreteCreator
public class B extends A {
#Override
protected Function createFunction() {
return (form) -> null; // return product
}
}
In this case the Product is fixed and not changable, but this could be overcome by mixing the two patterns together and including setStrategy(Function) again from class A in the first example.

Related

I am implementing factory design pattern in java

I am implementing factory design pattern in java where I want to keep one overloaded method in abstract class. Will it violate the factory pattern concept?
Or please suggest whether this is right way to implement Factory design pattern ?
abstract class A{
void meth(int a);
void meth(int a,int b);
}
class Factory{
public static A factoryMethod(int a){
if(a==1){
return new Ob1();
}else{
return new Ob2();
}
}
}
class Ob1 extends A{
void meth(int a){}
void meth(int a,int b){}
}
To implement the Factory Pattern first you need to consider what the Factory will produce. Let's produce Vehicles.
public VehicleFactory {
public Vehicle newVehicle(String type) {
...
}
}
which will produce Vehicles according to the class hierarchy below.
public interface Vehicle {
public List<Door> getDoors();
}
public class Motorcycle implements Vehicle {
public List<Door> getDoors() {
return Collections.<Door>emptyList();
}
}
public class SportsCar implements Vehicle {
public List<Door> getDoors() {
return Collections.<Door>unmodifiableList(Arrays.asList(new Door("driver"), new Door("passenger"));
}
}
public class Hatchback implements Vehicle {
public List<Door> getDoors() {
return Collections.<Door>unmodifiableList(Arrays.asList(new Door("driver"), new Door("passenger"), new Door("back"));
}
}
Then your VehicleFactory method newVehicle(...) might look like
public Vehicle newVehicle(String type) {
if ("motorcycle".equals(type)) { return new Motorcycle(); }
if ("sports car".equals(type)) { return new SportsCar(); }
if ("hatchback".equals(type)) { return new Hatchback(); }
return null;
}
Now the main question is "Why would you want to do this?"
Sometimes you want a nice clean interface for building a lot of
related items. You give the related items an Interface and a Factory
to build them. This allows someone using this part of the software to
simply pull in the Interface class and the ItemFactory. They don't
see the individual details, which simplifies their code.
Since you hid the implementation details of all of the Vehicles in the above code, if you had a programming error (or wanted to add something), you can fix one of the Vehicles (or add a new Vehicle) to the factory and re-release the library (JAR file) containing the VehicleFactory.
You know that other people have been using the VehicleFactory methods, so you don't have to worry about their code breaking at compile time, and unless you were careless, you can also assure that it will work at runtime.
This is not the same as saying that the behavior won't change. The new implementations of Vehicle will be returned back, hopefully with fewer embedded bugs. Also, since they didn't ask for the "new vehicles" you might have added they won't see them, until they call newVehicle("station wagon") or something like that.
Also, you can change how the Vehicles are built up. For example, if you later decide that you don't want a simple "just construct it in one pass" implementation style, you could alter 'newVehicle(...)' like so
public Vehicle newVehicle(String type) {
Chassis chassis;
if ("motorcycle".equals(type)) {
chassis = new TwoWheelChassis();
} else {
chassis = new FourWheelChassis();
}
return new ComponentVehicle(chassis, getDoorCount(type));
}
where ComponentVehicle implements Vehicle and for some reason requires an explicit Chassis object.
--- update seeing the "number of methods" question in the comments ---
A Factory pattern is not really about the number of methods, but about one method having the ability to build an abstract thing out of one or more concrete things.
So in the example above, I could have
public VehicleFactory {
public Vehicle newVehicle(String type) { ... }
public Vehicle newRedVehicle(String type) { ... }
public Vehicle newBlackVehicle(String type) { ... }
}
And they would all be acceptible factory methods with respect to the type of the Vehicle, but they would not be factory oriented methods with respect to the color of the Vehicle.
To get a factory method that could handle Type and Color at the same time, the factory method
public Vehicle newVehicle(String type, String color) { ... }
might be added. Note that sometimes some combinations just don't make any sense, so it might not be worthwhile packing all factory methods down into a single factory method.
Any method in your factory object is not really a factory method unless it has the potential to return back more than one base type of the interface. Likewise it is not a factory method if you have to specify how to build the object outside of the method.
If you need to pass control of how to build a Vehicle to the client of your "it would have been a factory" method while providing some security they used it in a sane manner, you want the Builder pattern. An example of how a Builder Pattern differs can be seen in the client code below
VehicleBuilder builder = new VehicleBuilder();
builder.addDoor("driver");
builder.addDoor("passenger");
builder.paintVehicle("red");
Vehicle vehicle = builder.getVehicle();
Factory pattern is a vague term, no? There are Simple factories, Factory methods, and Abstract factories. I think you're talking about a Simple Factory here. https://www.codeproject.com/Articles/1131770/Factory-Patterns-Simple-Factory-Pattern
Here is an example of Java factory implementation.
Let's say we have a requirement to create multiple currencies support and code should be extensible to accommodate new Currency as well. Here we have made Currency as interface and all currency would be a concrete implementation of Currency interface.
Factory Class will create Currency based upon country and return concrete implementation which will be stored in interface type. This makes code dynamic and extensible.
Here is complete code example of Factory pattern in Java.
The Currency classes:
interface Currency {
String getSymbol();
}
// Concrete Rupee Class code
class Rupee implements Currency {
#Override
public String getSymbol() {
return "Rs";
}
}
// Concrete SGD class Code
class SGDDollar implements Currency {
#Override
public String getSymbol() {
return "SGD";
}
}
// Concrete US Dollar code
class USDollar implements Currency {
#Override
public String getSymbol() {
return "USD";
}
}
The Factory:
// Factory Class code
class CurrencyFactory {
public static Currency createCurrency (String country) {
if (country. equalsIgnoreCase ("India")){
return new Rupee();
}else if(country. equalsIgnoreCase ("Singapore")){
return new SGDDollar();
}else if(country. equalsIgnoreCase ("US")){
return new USDollar();
}
throw new IllegalArgumentException("No such currency");
}
}
// Factory client code
public class Factory {
public static void main(String args[]) {
String country = args[0];
Currency rupee = CurrencyFactory.createCurrency(country);
System.out.println(rupee.getSymbol());
}
}
Check out for more Java Factory pattern examples.

Factory pattern: Accessing child methods

I have two classes CashStore and DrinkStore, both extends from Store. I have a StoreFactory class (returns Store object) to instantiate objects for clients. I want to access methods specific to child classes from these clients. How do I do it without casting? If I used casting, would it break the pattern, since now the clients know about the Child classes?
class Store{
A(){}
B(){}
}
class CashStore{
A(){}
B(){}
C(){}
D(){}
}
//impl for drink store and other stores
class StoreFactory{
public Store getStore(String type){
//return a Store obj based on type DrinkStore or CashStore
}
}
class Client{
StoreFactory fac;
public Client(){
fac = new StoreFactory();
Store s = fac.getStore("cash");
s.C(); //requires a cast
}
}
Does casting break my pattern?
Factory pattern is used to decouple from runtime type. For example, when it's platform- or layout-specific, and you don't want your client code to mess with it. In your case you do need an exact type, so it seems factory pattern isn't a good choice. Consider using simple static methods, like:
class Stores {
static CashStore createCashStore() {
return new CashStore();
}
static DrinkStore createDrinkStore() {
return new DrinkStore();
}
}
So basically you need to access child specific methods without casting. That's the whole purpose of Visitor pattern.
You can switch between different child by using method overloading. I have given an example below, you would need to adapt that to fit into your code. And also you should take out the business logic from the constructor (of Client) and implement them inside methods.
public class Client{
public void doSomething(CashStore cs){
cs.c();
//you can call methods specific to CashStore.
}
public void doSomething(DrinkStore ds){
ds.e();
//you can call methods specific to DrinkStore.
}
}
I want to access methods specific to child classes from these clients.
How do I do it without casting?
If you know the expected type, then you can use generics to avoid casting:
interface Store {
}
class WhiskeyStore implements Store {
}
class VodkaStore implements Store {
}
class StoreFactory {
<T extends Store> T getStore(Class<T> clazz) {
try {
// I use reflection just as an example, you can use whatever you want
return clazz.getConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException("Cannot create store of type: " + clazz, e);
}
}
}
public final class Example {
public static void main(String[] args) {
WhiskeyStore whiskeyStore = new StoreFactory().getStore(WhiskeyStore.class);
VodkaStore vodkaStore = new StoreFactory().getStore(VodkaStore.class);
}
}

Using a Factory to create a Strategy

I have the following Strategy Pattern implemented:
public abstract class RetrievalStrategy {
public abstract List<MyObject> retrieve();
}
public class LimitRetrievalStrategy extends RetrievalStrategy {
public int limit;
public LimitRetrievalStrategy(int limit) {
this.limit = limit;
}
public List<MyObject> retrieve() {
// fill up the list and return it, limiting to 'limit' results
return new ArrayList<MyObject>(limit);
}
}
public class SpeedRetrievalStrategy extends RetrievalStrategy {
public int speed;
public SpeedRetrievalStrategy(int speed) {
this.speed = speed;
}
public List<MyObject> retrieve() {
// do something with the speed and return list again
return new ArrayList<MyObject>();
}
}
My client application receives either a speed or a limit (and perhaps other parameters) from the user. I want to create a factory class that will return the proper strategy based on parameters that have a value and parameters that don't. I don't want the client the decide which Strategy should be returned. Should the factory createStrategy(params) method then have if statements for each parameter and depending on the different combinations (imagine there are other Strategy classes) return the Concrete Strategy class?
What is the proper way to do this?
Oh, RetrievalStrategyFactory, where to begin? This sounds like overengineering for a YAGNI. One approach is create an enum for specifying the "set" field, assuming there's one retrieval strategy per parameter, and use that as the factory.
public enum FieldParameter {
LIMIT {
RetrievalStrategy getRetrivalStrategy(int value) {
return new LimitRetrievalStrategy(value);
}
},
SPEED {
RetrievalStrategy getRetrivalStrategy(int value) {
return new SpeedRetrievalStrategy(value);
}
};
abstract RetrievalStrategy getRetrivalStrategy(int value);
}
Then the client code is not explicitly specifying the retrieval strategy, but it is implicitly given when the client code informs your code which field the user provided.
No, the return value in the method signature should be the common interface or base class.
The factory must have the if tests to decide on the concrete type to return, but that's unavoidable, unless you can craft a Map that returns a concrete instance based on a composite key class that encapsulates parameter combinations.
If you need the ability to extend a factory it you want an Abstract Factory. This is a factory of Factories. An Abstract Factory can have many plugin factories, which can follow a strategy to determine which factory is used.
This is usually needlessly complicated and something you can add later, so its not something you need to do just in case you might need it.

Extending class in Java and constructing using an instance of the extended class

I would like to extend a class and then copy the value from an instance of the class which has been extended, so I get all its parameters in my new class. In case this doesn't make sense, a simple example of what I'm trying to do:
public class MyTableModel extends DefaultTableModel {
public MyTableModel(DefaultTableModel model){
this = (MyTableModel) model; /* I realise this is invalid */
}
public newMethod(){
// Some additional code
}
}
Is this possible to achieve?
It looks like you want composition instead of inheritance. In particular, it looks like you're trying to use the decorator pattern. That is, you want to take an existing instance of DefaultTableModel, and create another DefaultTableModel that forwards most of the methods to the underlying delegate, but perhaps adding/modifying/decorating some functionalities.
You can never set this = somethingElse;, but you can have a DefaultTableModel delegate, and forward most/all requests to delegate, perhaps adding/decorating some methods as necessary.
See also
Effective Java 2nd Edition, Item 16: Favor composition over inheritance
Guava Example: ForwardingCollection
An example of this pattern is ForwardingCollection from Guava:
A java.util.Collection which forwards all its method calls to another collection. Subclasses should override one or more methods to modify the behavior of the backing collection as desired per the decorator pattern.
You can see the source code to see how this pattern is typically implemented:
#Override protected abstract Collection<E> delegate();
public int size() {
return delegate().size();
}
public boolean isEmpty() {
return delegate().isEmpty();
}
public boolean removeAll(Collection<?> collection) {
return delegate().removeAll(collection);
}
// many more interface Collection methods implemented like above...
As you can see, all the ForwardingCollection does is it implements Collection simply by forwarding all methods to its delegate(), another Collection. Understandably this is rather repetitive and mundane code to write, but now subclasses can simply extends ForwardingCollection and only decorate what they want to decorate.
You can't not set this in Java to anything, it is just used for expressions like (this == someObject) or accessing some property of the object being currently used like (this.someProperty) or inside a constructor to initialize the current object. See here for more info about the this keyword
This code will likely throw a java.lang.ClassCastException
That is MyTableModel is a DefaultTableModel but DefaultTableModel is not a MyTableModel. See http://java.sun.com/docs/books/jls/third_edition/html/conversions.html for more details about type conversion in java
If there is some state and/or behavior that you want to reuse from your parent class in your subclass you should consider marking those members as protected, or consider other form of composition.
A better way to do this would be to make the fields of the superclass protected instead of private - this will give you access to them in your subclass.
Note that when you defined the subclass constructor, you will need to call a constructor from the superclass as well, so in that respect you'll still be able to pass in all the required variables.
And don't forget that all public methods in the superclass can be called as-is by any code that has an instance of your subclass.
EDIT: A little example might help:
public class DefaultTableModel
{
protected String modelName;
protected int numberOfTables;
private numTimesReinited = 0;
public DefaultTableModel(String name, int numTabs)
{
modelName = name;
numberOfTables = numTabs;
}
public void reinit()
{
numTimesReinited++;
// Other stuff
}
protected int getNumberOfReinits()
{
return numTimesReinited;
}
public String getName()
{
return name;
}
}
public class MyTableModel extends DefaultTableModel
{
private String modelType;
public MyTableModel(String name, int numTables, String modelType)
{
super(name, numTables); // sets up the fields in the superclass
this.modelType = modelType;
}
// purely "local" code
public void getModelType()
{
return modelType;
}
// Accesses several protected data to provide new (public) functionality
public void addTable()
{
if (getNumberOfReinits() < 10)
{
numberOfTables++;
reinit();
}
}
}
Let me know if I've misunderstood your requirements, but it sounds like you want to access fields and behaviour of the superclass - which you'll have automatic access to in your subclass so long as they're not private.

Avoiding instanceof in Java

Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism". How would I do it in this case?
There are a number of subclasses of a base class; none of them are under my control. An analogous situation would be with the Java classes Integer, Double, BigDecimal etc.
if (obj instanceof Integer) {NumberStuff.handle((Integer)obj);}
else if (obj instanceof BigDecimal) {BigDecimalStuff.handle((BigDecimal)obj);}
else if (obj instanceof Double) {DoubleStuff.handle((Double)obj);}
I do have control over NumberStuff and so on.
I don't want to use many lines of code where a few lines would do. (Sometimes I make a HashMap mapping Integer.class to an instance of IntegerStuff, BigDecimal.class to an instance of BigDecimalStuff etc. But today I want something simpler.)
I'd like something as simple as this:
public static handle(Integer num) { ... }
public static handle(BigDecimal num) { ... }
But Java just doesn't work that way.
I'd like to use static methods when formatting. The things I'm formatting are composite, where a Thing1 can contain an array Thing2s and a Thing2 can contain an array of Thing1s. I had a problem when I implemented my formatters like this:
class Thing1Formatter {
private static Thing2Formatter thing2Formatter = new Thing2Formatter();
public format(Thing thing) {
thing2Formatter.format(thing.innerThing2);
}
}
class Thing2Formatter {
private static Thing1Formatter thing1Formatter = new Thing1Formatter();
public format(Thing2 thing) {
thing1Formatter.format(thing.innerThing1);
}
}
Yes, I know the HashMap and a bit more code can fix that too. But the "instanceof" seems so readable and maintainable by comparison. Is there anything simple but not smelly?
Note added 5/10/2010:
It turns out that new subclasses will probably be added in the future, and my existing code will have to handle them gracefully. The HashMap on Class won't work in that case because the Class won't be found. A chain of if statements, starting with the most specific and ending with the most general, is probably the best after all:
if (obj instanceof SubClass1) {
// Handle all the methods and properties of SubClass1
} else if (obj instanceof SubClass2) {
// Handle all the methods and properties of SubClass2
} else if (obj instanceof Interface3) {
// Unknown class but it implements Interface3
// so handle those methods and properties
} else if (obj instanceof Interface4) {
// likewise. May want to also handle case of
// object that implements both interfaces.
} else {
// New (unknown) subclass; do what I can with the base class
}
You might be interested in this entry from Steve Yegge's Amazon blog: "when polymorphism fails". Essentially he's addressing cases like this, when polymorphism causes more trouble than it solves.
The issue is that to use polymorphism you have to make the logic of "handle" part of each 'switching' class - i.e. Integer etc. in this case. Clearly this is not practical. Sometimes it isn't even logically the right place to put the code. He recommends the 'instanceof' approach as being the lesser of several evils.
As with all cases where you are forced to write smelly code, keep it buttoned up in one method (or at most one class) so that the smell doesn't leak out.
As highlighted in the comments, the visitor pattern would be a good choice. But without direct control over the target/acceptor/visitee you can't implement that pattern. Here's one way the visitor pattern could possibly still be used here even though you have no direct control over the subclasses by using wrappers (taking Integer as an example):
public class IntegerWrapper {
private Integer integer;
public IntegerWrapper(Integer anInteger){
integer = anInteger;
}
//Access the integer directly such as
public Integer getInteger() { return integer; }
//or method passthrough...
public int intValue() { return integer.intValue(); }
//then implement your visitor:
public void accept(NumericVisitor visitor) {
visitor.visit(this);
}
}
Of course, wrapping a final class might be considered a smell of its own but maybe it's a good fit with your subclasses. Personally, I don't think instanceof is that bad a smell here, especially if it is confined to one method and I would happily use it (probably over my own suggestion above). As you say, its quite readable, typesafe and maintainable. As always, keep it simple.
Instead of a huge if, you can put the instances you handle in a map (key: class, value: handler).
If the lookup by key returns null, call a special handler method which tries to find a matching handler (for example by calling isInstance() on every key in the map).
When a handler is found, register it under the new key.
This makes the general case fast and simple and allows you to handle inheritance.
You can use reflection:
public final class Handler {
public static void handle(Object o) {
try {
Method handler = Handler.class.getMethod("handle", o.getClass());
handler.invoke(null, o);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void handle(Integer num) { /* ... */ }
public static void handle(BigDecimal num) { /* ... */ }
// to handle new types, just add more handle methods...
}
You can expand on the idea to generically handle subclasses and classes that implement certain interfaces.
I think that the best solution is HashMap with Class as key and Handler as value. Note that HashMap based solution runs in constant algorithmic complexity θ(1), while the smelling chain of if-instanceof-else runs in linear algorithmic complexity O(N), where N is the number of links in the if-instanceof-else chain (i.e. the number of different classes to be handled). So the performance of HashMap based solution is asymptotically higher N times than the performance of if-instanceof-else chain solution.
Consider that you need to handle different descendants of Message class differently: Message1, Message2, etc. . Below is the code snippet for HashMap based handling.
public class YourClass {
private class Handler {
public void go(Message message) {
// the default implementation just notifies that it doesn't handle the message
System.out.println(
"Possibly due to a typo, empty handler is set to handle message of type %s : %s",
message.getClass().toString(), message.toString());
}
}
private Map<Class<? extends Message>, Handler> messageHandling =
new HashMap<Class<? extends Message>, Handler>();
// Constructor of your class is a place to initialize the message handling mechanism
public YourClass() {
messageHandling.put(Message1.class, new Handler() { public void go(Message message) {
//TODO: IMPLEMENT HERE SOMETHING APPROPRIATE FOR Message1
} });
messageHandling.put(Message2.class, new Handler() { public void go(Message message) {
//TODO: IMPLEMENT HERE SOMETHING APPROPRIATE FOR Message2
} });
// etc. for Message3, etc.
}
// The method in which you receive a variable of base class Message, but you need to
// handle it in accordance to of what derived type that instance is
public handleMessage(Message message) {
Handler handler = messageHandling.get(message.getClass());
if (handler == null) {
System.out.println(
"Don't know how to handle message of type %s : %s",
message.getClass().toString(), message.toString());
} else {
handler.go(message);
}
}
}
More info on usage of variables of type Class in Java: http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
You could consider the Chain of Responsibility pattern. For your first example, something like:
public abstract class StuffHandler {
private StuffHandler next;
public final boolean handle(Object o) {
boolean handled = doHandle(o);
if (handled) { return true; }
else if (next == null) { return false; }
else { return next.handle(o); }
}
public void setNext(StuffHandler next) { this.next = next; }
protected abstract boolean doHandle(Object o);
}
public class IntegerHandler extends StuffHandler {
#Override
protected boolean doHandle(Object o) {
if (!o instanceof Integer) {
return false;
}
NumberHandler.handle((Integer) o);
return true;
}
}
and then similarly for your other handlers. Then it's a case of stringing together the StuffHandlers in order (most specific to least specific, with a final 'fallback' handler), and your despatcher code is just firstHandler.handle(o);.
(An alternative is to, rather than using a chain, just have a List<StuffHandler> in your dispatcher class, and have it loop through the list until handle() returns true).
Just go with the instanceof. All the workarounds seem more complicated. Here is a blog post that talks about it: http://www.velocityreviews.com/forums/t302491-instanceof-not-always-bad-the-instanceof-myth.html
I have solved this problem using reflection (around 15 years back in pre Generics era).
GenericClass object = (GenericClass) Class.forName(specificClassName).newInstance();
I have defined one Generic Class ( abstract Base class). I have defined many concrete implementations of base class. Each concrete class will be loaded with className as parameter. This class name is defined as part of configuration.
Base class defines common state across all concrete classes and concrete classes will modify the state by overriding abstract rules defined in base class.
At that time, I don't know the name of this mechanism, which has been known as reflection.
Few more alternatives are listed in this article : Map and enum apart from reflection.
Add a method in BaseClass which returns name of the class. And override the methods with the specific class name
public class BaseClass{
// properties and methods
public String classType(){
return BaseClass.class.getSimpleName();
}
}
public class SubClass1 extends BaseClass{
// properties and methods
#Override
public String classType(){
return SubClass1.class.getSimpleName();
}
}
public class SubClass2 extends BaseClass{
// properties and methods
#Override
public String classType(){
return SubClass1.class.getSimpleName();
}
}
Now use the switch case in following way-
switch(obj.classType()){
case SubClass1:
// do subclass1 task
break;
case SubClass2:
// do subclass2 task
break;
}
What I use for Java 8:
void checkClass(Object object) {
if (object.getClass().toString().equals("class MyClass")) {
//your logic
}
}

Categories