Java method which takes unknown parameter - java

Is there a way in java to write a method which will take an unknown object as a parameter? The objects will always have a common method which the method will then need to call. Here is an example:
public void aMethod (MultipleObjects object){
object.commonMethod();
// Do some stuff here
}
I'm not sure what this is called (if it exists) so its difficult to search on Google.

You need an interface:
interface MyInterface {
void commonMethod();
}
class MyClass implements MyInterface {
// implement `commonMethod()`
}
Now your method would be:
public void aMethod(MyInterface object) {
...
object.commonMethod();
...
}
You can now pass an instance of MyClass (or any other class that implements MyInterface) to aMethod().

You can make all those classes (which share the common method) to implement an interface, so you define the method like:
public void aMethod(SomeInterface obj) {
obj.commonMethod();
// ...
}
The interface would be:
public interface SomeInterface {
public void commonMethod();
}

The usual way to do this is to define an interface that has just that method in it, then make sure all the classes that you might pass to aMethod implement that interface. E.g.:
interface CommonMethodHaver {
void commonMethod();
}
class Class1 implements CommonMethodHaver {
yadda yadda yadda;
void commonMethod() {
do class1-specific stuff here;
}
}
...
public void aMethod(CommonMethodHaver cmh) {
cmh.commonMethod();
// Do some stuff here
}

If you truly don't know what objects will be passed in and those object are not related through any kind of common base class or interface, then you will need to pass the object in as an Object reference and use reflection to find out if the object implements the method you want to call. If it does, then you again use reflection to call it.

I understand a lot of people are interpreting your question to mean you want to know about interfaces but I am interpreting this "write a method which will take an unknown object as a parameter?" to mean how do I write a method to handle unknown objects. As the other answers already tell you unless they share a common interface you can't have them all call the same method. But in case you are asking for this(which is what I think your question is asking for) this is how you would custom handle different unknown parameters...
public void aMethod(Object... object) {
if(object==null)
{
//whatever you want to do if no parameters are entered.
return;
}
for (Object o : object) {
if (o == null) {
continue; //what to do if null entered
}
if (o instanceof Integer) {
//whatever you want to do if it is an Integer
}
else if(o instanceof Double)
{
//whatever you want to do if it is a Double
}
else if(o instanceof Character)
{
//whatever you want to do if it is a Character
}
//and so on
}
}

Related

Java pass a class to check instance of

I want to pass a class to a function. In that function, new instance of other classes are created.
Then, I want to be able to find which object there is an instance of the class I passed:
public void doSomething(Class cls) {
SomeObject obj = new SomeObject();
if (obj instanceof cls) {
// Do amazing things here
}
}
class Person {
// This exists
}
doSomething(Person.class);
The code above doesn't work. I hope I'm clear enough what I'm trying to do.
You want to use https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#isInstance-java.lang.Object-.
if (cls.isInstance(obj)){
...
}
If you want to see if an object is an instance of a class type, you need to call isInstance:
if (cls.isInstance(obj)){
}
Or you can do isAssignableFrom:
if (clas.isAssignableFrom(obj.getClass())) {
}

Avoiding instanceof Java

I am trying to find a way to bypass the use of instanceof. I've created a class Item which has multiple subclasses like WeaponItem and BodyItem. Now I would like to make to do a call such as equip(Item) and it should determine by itself which overloaded function it should call such as equip(BodyItem).
Is there a way to bypass the use of instanceof for this case and what would you recommend? I've heard that in most cases using instanceof is bad practice and therefor I want to know what the alternatives are.
Code:
inv.equip(it); // inv = inventory object, it = Item
An example of equip function within inventory class how I preferably want it
public void equip(HelmItem it)
{
if (it != this.getHelm())
{
this.setHelm(it);
}
}
How I had it before:
public void equip(Item it)
{
if (it instanceof WeaponItem)
{
if (it != this.getWeapon())
{
this.setWeapon((WeaponItem) it);
}
} etc for all subclasses of item
}
Indeed, this could be solved with a visitor pattern.
However, it does not have to be a full-blown visitor, but a simplified variation of it. You could pass the inventory to the item and let the item do whatever it wants with it:
abstract class Item {
public abstract void equip(Inventory inv);
}
class HelmItem extends Item {
#Override
public void equip(Inventory inv) {
inv.setHelm(this);
}
}
class WeaponItem extends Item {
#Override
public void equip(Inventory inv) {
inv.setWeapon(this);
}
}
Then you can just call:
it.equip(inv)
without the instanceof operator.
Why not put the method in the Item concrete class, and it can equip itself? It's a little counter intuitive but it would solve your problem.
public class SomeConcreteItem extends Item {
public void equip(Body body) {
// Just an example.
body.getSections().get(0).equip(this);
}
}
That way, the concrete implementation knows how to equip itself and the classes that use it don't care. You can reference it by the Item superclass and provided that the Item superclass has an abstract method public void equip(Body body);, then you don't ever need to know about the concrete implementation and, therefore, no need for the instanceof operator.
A Note on Introducing a Design Pattern
You should be careful about introducing Design Patterns. People have a bad habit of leaping straight to a complicated pattern to solve a problem, when really something simpler and (in my opinion) more elegant is available.

Best way to differentiate between class types for different handling

I wanted to know what are the advantages / disadvantages of using each of the following ways to differentiate between sub-classes of the main parent class and handle them differently. I know this is pretty basic, but i couldnt find a full comparison between these ways anywhere.
For example:
- I have a Payment super abstract class and two extending classes OneTimePayment and Subscription
- I have a method switchPaymentState that should handle each one of these types differently
Option 1: Using instanceof
public void switchPaymentState(Payment payment) {
if(payment instanceof OneTimePayment) {
//do something
} else if(payment instanceof Subscription) {
//do something else
}
}
Option 2: Using enum type argument (or other...)
public enum PaymentType {
ONE_TIME_PAYMENT,
SUBSCRIPTION;
}
public abstract Payment(PaymentType type) {
this.type = type;
}
public OneTimePayment() {
super(ONE_TIME_PAYMENT);
}
public Subscription() {
super(SUBSCRIPTION);
}
and then:
public void switchPaymentState(Payment payment) {
switch(payment.type) {
case ONE_TIME_PAYMENT:
//do something
break;
case SUBSCRIPTION:
//do something
break;
}
}
Option 3: Using overload methods
public void switchPaymentState(OneTimePayment payment){
//do something
}
public void switchPaymentState(Subscription payment){
//do something
}
So, which is the best way to go (or a complete other way?) and why?
EDIT:
The operations i need to do based on the class type are NOT operations on the class itself, i need to take some data form the payment and send it via other services, so solutions like implementing this functionality inside the classes and calling it regardless of the type, will unfortunately not help in this case. Thanks!
The most modular way would be to use overriding.
You'll have a single switchPaymentState method which accepts the base type - Payment - and calls a method in the Payment class to do the handling. That method can be overridden in each sub-class of Payment.
public void switchPaymentState(Payment payment)
{
payment.handlePayment();
}
Your switchPaymentState method doesn't have to know which sub-classes of Payment exist, and it doesn't have to change if you add new sub-classes tomorrow.
Your option 3 will in many cases not work, because overloading is resolved atcompile-time rather than at run-time. If the type of your references is Payment, it is not possible to use overloading.
In terms of object-oriented design, using overridden methods is the "cleanest" method. However, it has the disadvantage that similar functionality is spead over multiple classes, whereas in the switch and instanceof solutions everything is together.
An alternative that offers the best of both worlds is the so-called Visitor Pattern. You create an interface PaymentVisitor with for each class you want a handle a method, as follows:
interface PaymentVisitor {
void visitOneTimePayment(OneTimePayment payment);
void visitSubscription(Subscription payment);
}
Then in you abstract superclass you add a method visit:
abstract class Payment {
...
abstract void callVisitor(PaymentVisitor visitor);
}
Which you implement in all you subclasses as follows:
class OneTimePayment {
...
#Override void callVisitor(PaymentVisitor visitor) {
visitor.handleOneTimePayment(this);
}
}
class Subscription {
...
#Override void callVisitor(PaymentVisitor visitor) {
visitor.handleSubscription(this);
}
}
Now, in all cases where you would otherwise write something like (in pseudo-Java):
switch (type of x) {
case OneTimePayment:
// Code
break;
case Subscription:
// Code
break;
}
You can now write, cleanly and type-safe:
x.callVisitor(new PaymentVisitor() {
#Override void handleOneTimePayment(OneTimePayment payment) {
// Code
}
#Override void handleSubscription(Subscription payment) {
// Code
}
});
Note also that the visitor is implemented in an inner class, so you still have access to all (effectively) final variables defined in the method body.
I think the switch is a bit of an anti-pattern regardless of how you do it. The more standard OO way would be to implement the same method or methods in both of the subclasses, and let each class manage things as appropriate. In other words
abstract class Payment {
abstract void processPayment(BigDecimal amount);
abstract void processRefund...
}
class OneTimePayment extends Payment {
void processPayment(BigDecimal amount){... }
void processRefund...
}
etc.
Also, unless you're reusing a considerable amount of code in the super class, consider an interface-based implementation instead of subclassing.

Command pattern with too many classes

Our legacy code has a long code of if else blocks that depend on events and object type
if(event == A && objectType == O1){
.....
}
else if (event == A && objectType == O2){
....
}
else if (....)
....
....
With more and more conditions introducing, I was thinking of replacing this logic with Command pattern for each condition. But the number of classes required would be (no. of events) * (no. of object types). Is there any simpler way to refactor this code?
Create a class enclosing event and objectType, make it implement .equals() and .hashCode(). Create a generic class for each execution block too.
Then you'll be able to use a Map and a simple lookup will return what is needed to execute.
The pattern you may be looking for is often called double dispatching or sometimes Visitor pattern. http://en.wikipedia.org/wiki/Visitor_pattern
Create a set of classes for events and a set for object types. Create an interface
public interface VisitEvent {
public void visit(EventA eventA);
public void visit(EventB eventB);
// for each event class
}
Within the event class, you have to invoke the visit pattern on the object type class.
public class EventA {
public void visit(ObjectTypeParent otp) {
otp.visit(this);
}
}
Presuming that the object type classes inherit from a common class
public abstract class ObjectTypeParent implements VisitEvent {
public void visit(EventA eventA) {
// default code here
}
// same for each event visit from VisitEvent
}
then
public class ObjectType01 extends ObjectTypeParent {
public void visit(EventA eventA) {
// stuff you want done for this combination
}
// don't implement the ones that have common behavior
}

Design of inheritance for Validate interfaces

I've never been so good at design because there are so many different possibilities and they all have pros and cons and I'm never sure which to go with. Anyway, here's my problem, I have a need for many different loosly related classes to have validation. However, some of these classes will need extra information to do the validation. I want to have a method validate that can be used to validate a Object and I want to determine if an Object is validatable with an interface, say Validatable. The following are the two basic solutions I can have.
interface Validatable {
public void validate() throws ValidateException;
}
interface Object1Validatable {
public void validate(Object1Converse converse) throws ValidateException;
}
class Object1 implements Object1Validatable {
...
public void validate() throws ValidateException {
throw new UnsupportedOperationException();
}
}
class Object2 implements Validatable {
...
public void validate() throws ValidateException {
...
}
}
This is the first solution whereby I have a general global interface that something that's validatable implements and I could use validate() to validate, but Object1 doesn't support this so it's kind of defunc, but Object2 does support it and so may many other classes.
Alternatively I could have the following which would leave me without a top level interface.
interface Object1Validatable {
public void validate(Object1Converse converse) throws ValidateException;
}
class Object1 implements Object1Validatable {
...
public void validate(Object1Converse converse) throws ValidateException {
...
}
}
interface Object2Validatable {
public void validate() throws ValidateException;
}
class Object2 implements Object2Validatable {
...
public void validate() throws ValidateException {
...
}
}
I think the main problem I have is that I'm kind of stuck on the idea of having a top level interface so that I can at least say X or Y Object is validatable.
what about this :
interface Validatable {
void validate(Validator v);
}
class Object1 implements Validatable{
void validate(Validator v){
v.foo
v.bar
}
}
class Object1Converse implements Validator{
//....
}
class Object2 implements Validatable{
void validate(Validator v){
//do whatever you need and ingore validator ?
}
}
What do you care if Object2 receives an unneeded argument ? if it is able to operatee correctly without it it can just ignore it right ?
If you are worried about introducing an unneeded dependency between object2 and Object1Converse then simply specify an interface to decouple them and use that as the validator.
Now I must add that having a mixed model where you have both object able to self validate and object which need external state information to validate sounds weird.
care to illustrate ?
Perhaps the apache commons validator project would be useful here - either directly or as a model for how to attack your problem. They effectively have a parallel set of objects that do the validation - so there is no interface on the objects, just the presence/absence of a related validator for the object/class.
This is in C#, but the same ideas can certainly be implemented in many other languages.
public class MyClass {
//Properties and methods here
}
public class MyClassValidator : IValidator<MyClass> {
IList<IValidatorError> IValidator.Validate(MyClass obj) {
//Perform some checks here
}
}
//...
public void RegisterValidators() {
Validators.Add<MyClassValidator>();
}
//...
public void PerformSomeLogic() {
var myobj = new MyClass { };
//Set some properties, call some methods, etc.
var v = Validators.Get<MyClass>();
if(v.GetErrors(myobj).Count() > 0)
throw new Exception();
SaveToDatabase(myobj);
}
As simple solution to the "can an object be validated" problem is to add a third interface.
This third interface is an empty one that parents both of the others, meaning you can just check against that interface (Assuming you aren't worried about someone spoofing being validate-able), and then iteratively check against the possible validation interfaces if you need to actually validate.
Example:
interface Validateable
{
}
interface EmptyValidateable inherits Validateable //Or is it implements?
{
void validate() throws ValidateException;
}
interface Objectvalidateable inherits Validateable
{
void validate(Object validateObj);
}

Categories