Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java parameter with undefined type

In python you don't have to specify the type of a function parameter. Is there a way to do this for a Java method parameter? If say I'm not sure what kind of argument will be input.

like image 644
user1925767 Avatar asked Dec 03 '25 11:12

user1925767


2 Answers

Try this with object or generics:

object:

public void foo(Object bar)
{

}

generics:

public <T> void foo(T bar) {

}

like image 190
Walery Strauch Avatar answered Dec 06 '25 01:12

Walery Strauch


Python, JavaScript and similar dynamically typed languages have objects that have arbitrary attributes, for example you may code:

someObj.someAttr

And it will return the attribute value if the type has such an attribute and it's been set, or a null otherwise.

The closest thing to this in java is a Map with String keys and Object values, so try this:

public void someMethod(Map<String, Object> map) {
    Object o = map.get("someAttr");
    // do something with o, which may be null
}
like image 45
Bohemian Avatar answered Dec 06 '25 01:12

Bohemian