Hello I have to make a frog catch a fly. I have been given the code they will use to test the method and they will use both
catchFly();
catchFly(3);
is there a way to cater for both possibilities if this were to happen, as I do not know how to check if there are nor arguments
public void catchFly()
{
super.catchFly();
account.credit(100);
super.yellow();
super.jump();
super.green();
}
First define the method which requires the argument:
public void catchFly(int value) {
super.catchFly();
account.credit(value);
super.yellow();
super.jump();
super.green();
}
Which you can use when the value is known:
catchFly(3);
Then for cases where the value isn't known, define an overload which supplies the hard-coded default value:
public void catchFly() {
catchFly(100);
}
Which you can call without an argument:
catchFly();
In cases like this the overloads are generally pass-through methods which invoke the main logic method, simply providing defaults where needed.
yes, it is possible, method overloading is the name for that
just define another method with the same name but other argument (see what is a signature of a method)
public void catchFly(int whatEver){
super.catchFly();
account.credit(whatEver);
super.yellow();
super.jump();
super.green();
}
Related
I have the following set of methods in different classes:
#ParameterizedTest
#MethodSource("com.myapp.AppleProvider#getApplesDependingOnConditions")
public void testSomething(Apple apple) {
SomeContainer.getInstance().setApple(apple)
// ...
}
The problem is that I cannot avoid copy/pase of the following
name argument for each test call
The very first line of each test - SomeContainer.getInstance().setApple(apple)
I tried to use extension points - BeforeTestExecutionCallback and BeforeEachCallback, but they don't seem to have ability to get parameter with which they are being called.
According to https://github.com/junit-team/junit5/issues/1139 and https://github.com/junit-team/junit5/issues/944 it's not possible to access argument passed to test from extension points yet and parameterized tests don't work for BeforeEach callbacks.
So I'm basically looking for any workaround so that my test could look like:
#MyAwesomeTest
public void testSomething() {
// ...
}
Where #MyAwesomeTest encapsulates two annotations above.
What I've already found:
In extension points the following data is available: displayname, method or tags. If I pass argument into the each test method (though it's very undesirable) looks like I can rely on displayname since it'll reflect argument passed to the method call for a particular parameter.
I'm trying to find out whether there're any other ways without need to add argument into each method.
I think you could cheat to get most of the way there:
public static Stream<String> apples() {
return com.myapp.AppleProvider
.getApplesDependingOnConditions()
.stream()
.peek(apple -> SomeContainer.getInstance().setApple(apple))
.map(apple -> { /* convert to name string */ })
}
#ParameterizedTest
#MethodSource("apples")
public void testSomething(String name) {
// ...
}
This question already has answers here:
Is it possible to have different return types for a overloaded method?
(13 answers)
The relationship of overload and method return type in Java?
(4 answers)
Closed 6 years ago.
I am gonna put this question to have a clear idea about overloading Concept in java . As per my understanding while method resolution in overloading compiler will look for method signature that is it should have same method name and different argument types . But what if the return type is different ??
class Test{
public void m1(int i) {
System.out.println(" int arg");
}
public int m1(String s) {
System.out.println("String-arg");
return (5+10);
}
public static void main (String[] args) throws java.lang.Exception
{
Test t = new Test();
t.m1(5);
int i = t.m1("ani");
System.out.println(i);
}}
the above program is running perfectly . my doubt here is , the method m1() is it overloaded ?? it has different return type . someone please make it clear. Thanks in advance
In Java methods are identified by name and arguments' classes and amount. The return type doesn't identify the method. For this reason the following code would be illegal:
public void m1(String i) {
System.out.println(" int arg");
}
public int m1(String s) {
System.out.println("String-arg");
return (5+10);
}
If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded. (...) When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4)
Summarizing, two methods with the same name can return different types, however it's not being taken into account when deciding which method to call. JVM first decides which method to call and later checks if the return type of that method can be assigned to the certain variable.
Example (try to avoid such constructions):
public int pingPong(int i) {
return i;
}
public String pingPong(String s) {
return s;
}
public boolean pingPong(boolean b) {
return b;
}
if we follow the Oracle definition then yes, it is a overloaded method
here the info (emphasis mine)
The Java programming language supports overloading methods, and Java
can distinguish between methods with different method signatures. This
means that methods within a class can have the same name if they have
different parameter lists (there are some qualifications to this that
will be discussed in the lesson titled "Interfaces and Inheritance").
the fact that the method return a value or not is IRRELEVANT for the overloading definition...
another thing is here why can a method somethimes return a value and sometimes no...
this will drive crazy the people using the code, but that is another question...
For example, there is a method public void set_gender(String gender) {}, make sure only "male" or "female" is passed to this method without using enumeration.
Also, how to meet this demand when the method declaration is public void set_gender(String... params) {}?
If there's no such way to realize this, how could I give a warning in IDE when someone is passing a string that this method could not understand, just like how it works in Android Studio when I'm passing a value that is not a flag that defined inside a certain Class.
These are 4 ways I could think of:
Use pre-defined method without parameter:
public void setMale() { /* TODO: Implement */ }
public void setFemale() { /* TODO: Implement */ }
Keep setGender() but use boolean values as its parameter instead of plain String. true means it's male, false female (or the other way around):
public void setGender(boolean male) { /* TODO: Implement */ }
Keep setGender() while using String as its parameter, and throw an IllegalArgumentException if the supplied parameter does not comply with the scope:
public void setGender(String gender) {
if (!"male".equalsIgnoreCase(gender) && !"female".equalsIgnoreCase(gender)) {
throw new IllegalArgumentException("Bad parameter");
}
/* TODO: Implement */
}
Just use enums which, frankly, was designed with this exact use cases in mind. Or IntDef if you're really that worried about performance.
Oh, and as an addition, this question you asked:
If there's no such way to realize this, how could I give a warning in
IDE when someone is passing a string that this method could not
understand, just like how it works in Android Studio when I'm passing
a value that is not a flag that defined inside a certain Class.
They achieve this by using IntDef. ;)
There is StringDef annotation for such cases. You can mark parameter with it and then check it in runtime to verify.
Is there a way, using Java Reflection or otherwise, by which a method can retrieve its own name? Preferably as a string.
Context:- I have a method, which calls another method which would take as input the name of the first method. So I need a way for the first method to be aware of its own name..
Example:-
public class Example
{
static void exampleMethod1()
{
exampleMethod2(name_of_exampleMethod1);
}
static void exampleMethod2(String value)
{
-------some code------------
}
}
As an alternative, you can get it from the current stack:
System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName())
What you ask for can be done by analyzing the stack trace:
new Throwable().getStackTrace()[0].getMethodName();
well I'm wondering if it's possible to have a method where another method is passed as a parameter, so the first method can call the method passed in param?
Like for instance:
public void goToVisitManagementForm() throws ParseException {
if (isAuthenticated() && userTypeIs("Patient")) {
// I could have this whole block just moved to another method?
Panel newPanel = new Panel("Choose the details for your visit");
Component visitManagementForm = new VisitManagementForm(userData,
this);
newPanel.addComponent(visitManagementForm);
mainWindow.setMainPanel(newPanel);
} else {
authenticate();
}
}
If the code block would be moved to another method and it would be passed as a parameter to this method. How can I achieve that and is this a good practice? Because in this case I have the ifs that I always need to paste in...
What about other aspects of this?
This is called a higher-order function and you cannot do this in Java 7 or below. You can simulate passing functions to other functions through the use of an anonymous class that instantiates some interface the function expects, and then calling the function on that object.
For example, to pass a no-arg function:
interface Function {
void apply();
}
void takesAFunction(Function function) {
function.apply();
}
Then the following code snippet would do what you want:
Function myFunction = new Function() {
#Override
public void apply() {
// your code here.
}
};
takesAFunction(myFunction);
As a side note, reflection is extreme overkill for this type of problem.
You can pass methods as parameters using Java Reflection API.
First, you get a method object from a class:
Class c = MyClass.class;
Method[] methods = c.getMethods();
Method m = // choose the method you want
Then your function can take a Method object as a parameter:
public void aFunction(MyClass o, Method m);
And then inside that function you can invoke the method:
m.invoke(o);
This is a very simple example, where the method doesn't take any parameters. It's pretty easy to expand on this example and add the parameters as well.
Yes, but it is a very advanced procedure. You need to use the Method object. Here is the javadoc on Method:
here is the javadoc:
- http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Method.html
If I am understanding your question correctly, you want to be able to pass a method as a parameter. There really is no 'smooth' way to do this in Java. In objective C, it is built right into the language, (#selector tag)