I have created a hash table that will keep as a key a string that will represent the name of the method that the user will give, and as value the actual method call, as string too. The code I am using is the one here:
public void getMethod(String givenMethod){
Map<String, String> methods = new HashMap<String, String>();
methods.put("length", "length();");
methods.get(givenMethod);
}
From the main method I call objectX.getMethod("length");, but the method length(); is not executed. Can someone help me please?
You are getting the method but you are not invoking it. You'll have to do something like this:
Method yourMethod = objectX.getClass().getDeclaredMethod("yourMethodName"); //This is the string that represents the name of the method.
Then you invoke the method. All this through reflection:
yourMethod.invoke(YourObject);
The parameter of the invoke method is first the object, and then the attributes.
You can also get the return type of the method and cast the result, since the invoking the method will result in an Object type method:
yourMethod.getReturnType(); //This line gives you the type returned by your method.
Use Java **reflection to call method by its name (as you said you are storing method name in map).
For more detail read following article :
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
You need to use reflection to call a method by name. So your data structure would look more like
Map<String, Method> meth = new Hashmap<String,Method>();
Where Method is an actual object.
Related
I am trying to mock a static method of enum which has null value like below
try (MockedStatic<SomEnum> e = Mockito.mockStatic(SomEnum.class)) {
e.when(() -> SomEnum.methodWhichAcceptingNullParam(any())).thenReturn(somValue);
}
here any() is not working... i am not sure I am passing null parameter inside method
methodWhichAcceptingNullParam
I have tried both any and isNull.The fact is SomEnum.methodWhichAcceptingNullParam is always get called however it should not because I provided a mocked value already
any help?
Is your code called with a null or not-null object? This information is missing (at least for me).
Assuming you are calling SomeEnum.methodWhichAcceptingNullParam(null), then you need to use
ArgumentMatchers.isNull()
instead of any().
I am trying to write an interceptor using javax interceptor api. It has to log the arguments passed to a method and the return value of the method.
Below is a sample code snippet which logs the arguments
for(final Object object: context.getParameters()) {
final Methods[] methods = object.getClass().getMethods();
for(final Method method: methods){ if(method.getName().startsWith("get")) {
LOGGER.info(method.getName() + ":" + method.invoke(object));
}
}
}
I am having trouble logging complex/user-defined types.
Let's say there is a getter method which returns students address of type Address. My code does not check if the invoke method returns primitive or user defined type. So it prints hash code of Address when getAddress method is invoked.
I know that I have to write some kind of recursive code by checking the return type of the getter method. If the getter method returns user defined type then I will again use reflection to find all getter method and then print them.
To do this I have to use a if else condition something like below
Pseudo code:
type =method.getReturnType().getSimpleName();
if type != string or int or char or boolean and so on
then
Call the recursive method which again does the above
I want to know if there is a better solution. How do I solve this problem?
use method.getReturnType().isPrimitive()
https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isPrimitive%28%29
you can find some other is...() methods that can be useful to you
May be we can use Jackson Mapper api and just pass the instance to the mapper and print the result to the log.
I think this is the easiest way.
I am new to Mockito, I am trying to verify the attributes of an object which gets created inside a method.
pseudo code below:
class A{
...
public String methodToTest(){
Parameter params = new Parameter(); //param is basically like a hashmap
params.add("action", "submit");
return process(params);
}
...
public String process(Parameter params){
//do some work based on params
return "done";
}
}
I want to test 2 things:
when I called methodToTest, process() method is called
process() method is called with the correct params containing action "submit"
I was able to verify that process() is eventually called easily using Mockito.verify().
However trying to check that params contains action "submit" is very difficult so far.
I have tried the following but it doesn't work :(
BaseMatcher<Parameter> paramIsCorrect = new BaseMatcher<Parameter>(){
#Overrides
public boolean matches(Object param){
return ("submit".equals((Parameter)param.get("action")));
}
//#Overrides description but do nothing
}
A mockA = mock(A);
A realA = new A();
realA.methodToTest();
verify(mockA).process(argThat(paramIsCorrect))
Any suggestion ?
If you have got verify() to work, presumably it is just a case of using an argument matcher to check the contains of params.
http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#3
The example given in the above docs is verify(mockedList).get(anyInt()). You can also say verify(mockedList).get(argThat(myCustomMatcher)).
As an aside, it sounds like you are mocking the class under test. I've found that this usually means I haven't thought clearly about either my class or my test or both. In your example, you should be able to test that methodToTest() returns the right result irrespective of whether or not it calls process() because it returns a String. The mockito folk have lots of good documentation about this sort thing, particularly the "monkey island" blog: http://monkeyisland.pl/.
Just pass Parameter in as a constructor argument to a constructor of the class A, then use a mocked instance/implementation of Parameter in your test and verify on the mock. That is how it is normally done - you separate your classes and compose them using constructor injection, that enables you to pass in mocks for testing purposes (it also allows rewiring the application and exchanging some commons a lot easier).
If you need to create Parameter on every function invocation you should use a factory that creates Parameter instances and pass that in. Then you can verify on the factory as well as the object created by the factory.
I am trying to get the first value of a map by following
TreeMap<String, String> myMap = new TreeMap<String, String>();
myMap.put("key1","value1");
myMap.put("key2","value2");
String first = myMap.firstEntry().getValue();
String firstOther = myMap.get(myMap.firstKey());
its working for me writing in Java
In same i am using expression in jsf like following
${criterion.variableBindings.firstEntry.getValue()}
In this scenario I didn't get the value.
Please # for the calling method or variable of a bean class..
#{criterion.variableBindings.firstEntry.getValue()}
If you didn't get for for above
create a variable inside bean class setter and getter then access that variable in jsf file.
In bean
private String first ;
first = myMap.firstEntry().getValue();
//setterand getter
in jsp
#{bean.first}
You're trying to invoke the method firstEntry, so you need to use method invocation syntax, which has parentheses after the method name:
${criterion.variableBindings.firstEntry().getValue()}
If the method had been named getFirstEntry you could have accessed it as a property as well, but since it does not start with get you need to access it as a method.
This question is being asked everywhere on Google but I'm still having trouble with it. Here is what I'm trying to do. So like my title states, I'm getting an 'object is not an instance of declaring class' error. Any ideas? Thanks!
Main.java
Class<?> base = Class.forName("server.functions.TestFunction");
Method serverMethod = base.getMethod("execute", HashMap.class);
serverMethod.invoke(base, new HashMap<String, String>());
TestFunction.java
package server.functions;
import java.util.HashMap;
import java.util.Map;
import server.*;
public class TestFunction extends ServerBase {
public String execute(HashMap<String, String> params)
{
return "Test function successfully called";
}
}
You're invoking the method with the class, but you need an instance of it. Try this:
serverMethod.invoke(base.newInstance(), new HashMap<String, String>());
You are trying to invoke the execute method on the object base, which is actually a Class object returned by your Class.forName() call.
This would work for a static (class) method - but execute is a non-static (instance) method.
(It would also work for calling an instance method of an object of type Class - but that's not what you are trying to achieve here!)
You need an actual instance of TestFunction to invoke the method on, or you need to make the method static.
When invoking a static method by reflection, the first argument to invoke() is ignored, so it is conventional to set it to null, which clarifies the fact that there's no instance involved.
Although your current example method would do the same thing for any TestFunction object, in general an instance method could produce a different result for each object - so the .invoke() reflection method needs to know which object to run the method on.