Is there a way in IntelliJ to make a usage search of a method and filter this by specific arguments passed to the method? - intellij-idea

I have a method in my Service class which executes an hibernate update for any domain object:
update(Object obj)
It's called from lot's of classes in my project for different kind of objects. I would like to find all usages of this method when it's called for a specific domain object. I.e. call methods call wich executes an update of my Title object:
serviceClass.update(Title title)
I'm using IntelliJ as my IDE and I'm wondering if there is a way to find all those usages.
Does anyone have an IDEA how to do this?
Thanks a lot in advance,
Ronny

I've tried it with a small sample project and was able to achieve the desired behavior using Structural Search and Replace feature with the modified method calls template:
$MethodCall$ Text constraints, Text/regexp should be set to update so that methods with other names are ignored. $Parameter$ Occurrences count, Minimum count should be set to 1 to ignore method calls with no or more parameters.
Results:

If you're interested in the call chains that are providing a specific input into a given method, try the Analyze->Data Flow to Here command.
This allows you to see which values are passed in, through which call chains. And, for example, where null values might be coming from.
Quite a powerful feature, really.

Related

From a ByteBuddy-generated method, how do I set a (public) instance field in an object received as an argument to the return value of a MethodCall?

I am generating a class in ByteBuddy.
As part of one method implementation, I would like to set a (let's just say) public instance field in another object to the return value of a MethodCall invocation. (Keeping the example public means that access checks etc. are irrelevant.)
I thought I could use MethodCall#setsField(FieldDescription) to do this.
But from my prior question related to this I learned that MethodCall#setsField(FieldDescription) is intended to work only on fields of the instrumented type, and, looking at it now, I'm not entirely sure why or how I thought it was ever going to work.
So: is there a way for a ByteBuddy-generated method implementation to set an instance field of another object to the return value of a method invocation?
If it matters, the "instrumented method" (in ByteBuddy's terminology) accepts the object whose field I want to set as an argument. Naïvely I'd expect to be able to do something like:
MethodCall.invoke(someMethod).setsField(somePublicField).onArgument(2);
There may be problems here that I am not seeing but I was slightly surprised not to see this DSL option. (It may not exist for perfectly good reasons; I just don't know what they would be.)
This is not possible as of Byte Buddy 1.10.18, the mechanism was originally created to support getters/setters when defining beans, for example. That said, it would not be difficult to add; I think it would even be easiest to allow any custom byte code to be dispatched as a consumer of the method call.
I will look into how this can be done, but as a new feature, this will take some time before I find the empty space to do so. The change is tracked on GitHub.

vb pass name of function using intellisense

I'm tying to implement a novel way of overriding functions based on which DLLs I have loaded. In this model, I have a list of class instances from First = Highest Priority to Last = Lowest priority.
Any of those classes may implement a Hook function or callback. I'm currently at the stage where I can pass a string to a function, and then call it - my library convention looks like this:
Dim hookclasses as HooksList
Dim callable as Object
hookclasses.Add(new ClassA)
hookclasses.Add(new ClassB)
'... etc.
if hookclasses.Has("MyHookFunction", callable) then
callable.MyHookFunction()
end if
This all works, but I'd like to reduce typos by leveraging Intellisense. I've already thought of popping the strings into a class containing constant strings, so I'm after something better than that.
Ideally I'd like to have a fallback class that implements all of the hook functions (even if it simply returns), and if the language supported it, I'd like to do the following:
if hookclasses.Has(NameOf(FallbackClass.MyHookFunction), callable) then ...
Clearly there is no 'NameOf' operator, and I don't know how to write a NameOf function.
Is this possible?
Thanks.
Check this article nameOf (C# and Visual Basic reference)
https://msdn.microsoft.com/en-us/library/dn986596.aspx
It does exactly what you want. And before that String Litterals were almost the only option.
Edit :
Question was : "Clearly there is no 'NameOf' operator, and I don't know how to write a NameOf function."
If I understand your problem right, you have a list of classes that you fetched from dynamically loaded DLL, point is you don't know if a class implements all of the hooks or only a few.
If you use an interface, like IHookable and put all the hook functions in there, it means all the DLL have to implement all the hook functions, which is not what you want.
And (if I understand it properly) if the first class in list does not implement the hook, you check the second one and so on. So with an interface you wouldn't know if the hook is implemented or not.

unit tests - white box vs. black box strategies

I found, that when I writing unit tests, especially for methods who do not return the value, I mostly write tests in white box testing manner. I could use reflection to read private data to check is it in the proper state after method execution, etc...
this approach has a lot of limitation, most important of which is
You need to change your tests if you rework method, even is API stay
the same
It's wrong from information hiding (encapsulation) point of view -
tests is a good documentation for our code, so person who will read
it could get some unnecessary info about implementation
But, if method do not return a value and operate with private data, so it's start's very hard (almost impossible) to test like with a black-box testing paradigm.
So, any ideas for a good solution in that problem?
White box testing means that you necessarily have to pull some of the wiring out on the table to hook up your instruments. Stuff I've found helpful:
1) One monolithic sequence of code, that I inherited and didn't want to rewrite, I was able to instrument by putting a state class variable into, and then setting the state as each step passed. Then I tested with different data and matched up the expected state with the actual state.
2) Create mocks for any method calls of your method under test. Check to see that the mock was called as expected.
3) Make needed properties into protected instead of private, and create a sub-class that I actually tested. The sub-class allowed me to inspect the state.
I could use reflection to read private data to check is it in the proper state after method execution
This can really be a great problem for maintenance of your test suite
in .Net instead you could use internal access modifier, so you could use the InternalsVisibleToAttribute in your class library to make your internal types visible to your unit test project.
The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly
This will not resolve every testing difficulty, but can help
Reference

Intellij filtering Find Usages/Call hierarchy

I need to do important refactoring in a framework. I have a method called about 300 times from various locations in the code (i.e. Find Usages give me about 300 results).
I would like to filter those results so that it only return usages that are not in the body of a constructor.
I tried to use "view call hierarchy", it gives more readable results (i.e. it's more easy to identify call from outside constructor). But I was wondering if there is a way to exclude automatically calls that are done from within a constructor body?
I'm not used to work with the "structural search", but it's maybe something that can help ?
I'm using IDEA EAP 12
(Answering my own question)
I tried to explore features of SSR and finally found an helpful pattern.
What I want : find all calls to method myMethod that are done, but excluding those that are done inside constructor body (i.e. only those that are done in a regular instance method).
The search pattern:
class $Class$ {
$ReturnType$ $MethodName$($ParameterType$ $Parameter$) {$MethodCode$;}
}
This pattern will match all non empty methods. So I still have to restrict $MethodCode$ with a regexp:
.*\.myMethod\(.*
I think it should be possible to improve $MethodCode$ regexp, but I didn't get any false match... so I'm happy with that.

What is the use of reflection in Java/C# etc [duplicate]

This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.