Quote (Eep @ Apr 29 2015 11:52pm)
since you guys are out and about tonight -
can anyone offer me a decent website to explain REAL WORLD USE CASES for reflection?
I get introspection, but I read somewhere that introspection is only a part of reflection....that reflection gives us some more power.
I just can't find a single goddamn explanation I understand.
edit:
So far, from what I've read, reflection is apparently:
1: Introspection (getting information about an object at run time, for example)
2: You can invoke methods via strings.
and that is it
there are other use cases. we used it at my internship to get around circular dependencies for factories.
so we have a few dozen Entities, each in a different project, and some Entities implement ITaskOwner which is in a common project. so we have a TaskOwnerType (which refers to the entity) and a TaskOwnerId (surrogate key per table). and we have a general screen that explains a Task and you need to see the TaskOwner. so we have a TaskOwnerFactory. normally, you'd try something like this:
Code
public ITaskOwner getTaskOwner(taskOwnerType, taskOwnerId){
ITaskOwner taskOwner = null;
if (taskOwnerType == TaskOwnerType.Document){
taskOwner = new Document().findById(taskOwnerId);
} else if (taskOwnerType == TaskOwnerType.Policy){
taskOwner = new Policy().findById(taskOwnerId);
}
// etc
}
unfortunately, we have a problem. ITaskOwner is part of a "Common" project which all our other projects use as a library. so, if we tried to use the Document class here, we'd get a circular reference and it won't compile. but we can get around that using reflection.
i can't remember the syntax offhand, but something like:
taskOwner = ((Entity)Activator.CreateInstance(Typeof("com.blah.blah.Document"))).findById(taskOwnerId);
by using the full name of the class, we can use reflection to create the instance