Why do we need to instantiate a type at run time? - reflection

I am new to the usage of reflection in Java/scala. It is not quite clear to me why we need to instantiate a type at runtime. An example would be the best. Thanks a lot.

I will give you a general example of where runtime type instantiation or in general inspection of a types is useful. Think of the Plugin Pattern. Assume you want to create an application that allows users to create plugins. You don't have the plugins the users are going to make in the future, at hand. How are you able to use their plugins after you have released your application? You need to be able to inspect their plugins for a method your application requires and then call said method.
In order to enable this, language designers create a platform in which you are able to query a module (jar in java, assemblies in .net) for the types it defines and the methods, fields, etc it contains. You can then call any method, instantiate any type you want and basically interact with the module as if you had the module at compile time and you were referencing it(well not exactly but you get the point).
Here's and example of a method call that happens at runtime. You can assume that we have already created foo from a string we get from a configuration file at runtime. foo was specified as the name of the jar file containing the plugin types. I don't want to provide the instantiation code as it would make this too bloated, but here is the method:
Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);
As you see, we basically got the type of the class foo, we queried it for a method using the method's name and then called it. By doing so we extended the functionality of our program with the plugin at runtime.

Related

Show nested usages in IntelliJ IDEA

In IntelliJ IDEA, is there a way to see usages of a method nested in other usages?
I have a symfony2 app that has a class MyClass with method myMethod() this method is used in a bunch of services and controllers. I would like to trace all usages of this method all the way up to controllers that are linked to the app's routes. As a result, I would have a list of routes and corresponding controllers/methods that directly or indirectly use myMethod(). Is it possible?
In Java, it's Cmd-Alt-H (Ctrl-Alt-H on Windows), so I assume it's the same in PHP.
It's called "Call hierarchy". So you can use Cmd-shift-A (resp. Ctrl-shift-A and type "Call hierarchy" to find it.

Metadata for Exceptions thrown by a class

Flash builder lets me insert metadata for events fired by a class, example:
[Event("myEvent", "flash.events.Event")]
public class MyClass() {
}
Is there any way to do the same for Exceptions?
Currently I have checked here, and can't see it documented. Perhaps it's not even worthwhile, what are your thoughts.
There are ways to create your own metadata; and add that into your app at compile time. Use the keep-as3-metadata compiler argument.
It will be up to you to write code to do something with it at runtime; or to build IDE extensions to make use of the code while writing the code.
To access such metadata at runtime, you'll need to perform some type of introspection. Here are some docs and another StackOverflow Question about this.
Many Flex Frameworks make use of custom metadata.

Lazy type registration using Unity App bloc

Is it possible to registe the type (container.RegisterType()) in such a way that the type gets registered in container when the type is asked for using container.Resolve<> Method.
I measn someting like Lazy Registration?
container.RegisterType(typeof(IType), typeof(ConcreteType));
var obj = _container.Resolve<IType>();
Is it also possible by doing configuration in config file?
Out of the box: No. Unity does quite some pre-processing (like looking up constructors, emitting IL code for fast object creation etc.) at registration time. It does not matter wether you use a config file or code for configuration.
What is your scenario for "lazy registration"? Isn't lazy instantiation enough? I never had a situation where the registration phase was that performance critical.

How does ninject work at a high level, how does it intercept object instantiation?

At a high level, how do these dep. injection frameworks work?
I can understand if you always instantiate an object via a custom factory like:
IUser user = DepInjector.Get<User>();
I'm guessing what happens is, wherever you defined the mappings, it will look at the type you want and try and find a match, if found, it will via reflection instantiate the type.
Are there dep. inj. frameworks that would work like:
IUser user = new User();
If so, how would it get the correct user, where is it hooking into the CLR to do this? In case of an asp.net website, is it any different?
If you want to know how Ninject works then the obvious place to start would be reading How Injection Works on their official wiki. It does use reflection but it now also uses dynamic methods:
"By default, the StandardKernel will
create dynamic methods (via
System.Reflection.Emit.DynamicMethod)
that can be used to inject values into
the different injection targets. These
dynamic methods are then triggered via
delegate calls."
As for you second example, I don't believe there are any DI frameworks that would do what you ask. However, constructor injection tends to be most common way of implementing IoC, so that when a class is constructed it knows what type to bind to via some configuration binding. So in your example IUser would be mapped to concrete User in config bindings so that any consuming class that has an IUser parameter as part of its constructor would get the correct User type passed in.
AFAIK there's no way to "hook into" object instantiation with the CLR. The only way to use DI in the second case would be to employ an assembly rewriter (i.e. a postprocessor similar to PostSharp) to replace the call to new with a call to the DI factory method (i.e. GetUser) in the compiled code.

why are some IronPython dlls generated with a DLRCachedCode class inside?

when I compile some .py codefiles with no class definitions into dlls , the compiled dll is created with a "DRLCachedCode" class inside. Why is that?
When you compile IronPython code it doesn't get compiled to normal .NET code where you'd have a class at the IL level for each class you have at the source level. Instead it gets compiled into the same form that we compile to internally using the DLR.
For user code this is just a bunch of executable methods. There's one method for each module, function definition, and class definition. When the module code runs it executes against a dictionary. Depending on what you do in the module the .NET method may publish into the dictionary a:
PythonType for new-style classes
An OldClass for old-style classes
A PythonFunction object for function
definitions
Any values that you assign to (e.g.
Foo=42)
Any side effects of doing exec w/o providing a dictionary (e.g. exec "x=42")
etc...
The final piece of the puzzle is where is this dictionary stored and how do you get at it? The dictionary is stored in a PythonModule object and we create it when the user imports the pre-compiled module and then we execute the module against it. Therefore this code is only available via Python's import statement (or the extension method on ScriptEngine "ImportModule" which is exposed via IronPython.Hosting.Python class).
So all of the layout of the code is considered an internal implementation detail which we reserve the right to change at any point in time.
Finally the name DLRCachedCode comes because the DLR (outer layer) saves this code for us. Multiple languages can actually be saved into a single DLL if someone really wanted to.
This link answers the question: http://www.ironpython.info/index.php/Using_Compiled_Python_Classes_from_.NET/CSharp_IP_2.6 how to access an IronPython class from C#.
Manual compilation: \IronPython 2.7\Tools\Scripts>ipy pyc.py /out:MyClass /target:dll MyClass.py did not work. Only when I used SharpDevelop with IronPython it worked as in the post.

Resources