Inspecting your application structure from code with Introspection

Introspection is a way for you to get information about your application structure at runtime. For example, you could use it to get a list of the methods of a class instance, check for a specific method and then call that method. Introspection is a module containing the various methods that can act on class instances. For example, this code gets the type (name) of a class instance:

Var f As New FolderItem
Var oType As Introspection.TypeInfo
oType = Introspection.GetType(f)
MessageBox(oType.FullName)

The above code is not really useful because you already know the type since your code declared it. But if you are writing a more generic method that does not know much about the code that is calling it, introspection starts to become much more useful.

In fact, introspection is most useful when you are writing generic code that is designed to be used in a wide variety of places. This type of code is often called framework code.

Some examples of when introspection can be useful:

  • A unit testing library could use introspection to run methods that end in "test".

  • A database framework could use introspection to get the type of properties on a class in order to create database columns for them.

  • A serialization library could use introspection to query a class so that its information can be saved and restored.

A simpler, but still interesting use is in the App.UnhandledException event handler. Here, you usually want to display the type of exception that occurred. You would normally do this using a long Select...Case statement for each type of exception. The problem with doing it this way, is that it makes your app larger because all the related code for the exception is pulled into your app, even if you do not need it. It also leads to more complicated code and requires you to remember every exception name and update the code when new exceptions are added.

Instead you can use introspection to get the type of the RuntimeException parameter of the UnhandledException event handler. This code displays the type of the runtime error followed by the stack trace:

Var excType As Introspection.TypeInfo
excType = Introspection.GetType(error)

Var excName As String
excName = excType.FullName

Var stack As String
stack = String.FromArray(error.Stack, EndOfLine)

Var errMsg As String
errMsg = excName + EndOfLine + EndOfLine + stack

MessageBox(errMsg)
Return True

See also

Introspection module