reflection interview questions
Top reflection frequently asked interview questions
I have a generic class in my project with derived classes.
public class GenericClass<T> : GenericInterface<T>
{
}
public class Test : GenericClass<SomeType>
{
}
Is there any way to find out if a Type
object is derived from GenericClass
?
t.IsSubclassOf(typeof(GenericClass<>))
does not work.
Source: (StackOverflow)
What is reflection, and why is it useful?
I'm particularly interested in Java, but I assume the principles are the same in any language.
Source: (StackOverflow)
How can I check whether a variable is defined in Ruby? Is there an isset
-type method available?
Source: (StackOverflow)
One may not always know the Type of an object at compile-time, but may need to create an instance of the Type. How do you get a new object instance from a Type?
Source: (StackOverflow)
If I have two variables:
Object obj;
String methodName = "getName";
Without knowing the class of obj
, how can I call the method identified by methodName
on it?
The method being called has no parameters, and a String
return value. It's a getter for a Java bean.
Source: (StackOverflow)
Due to the implementation of Java generics, you can't have code like this:
public class GenSet<E> {
private E a[];
public GenSet() {
a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation
}
}
How can I implement this while maintaining type safety?
I saw a solution on the Java forums that goes like this:
import java.lang.reflect.Array;
class Stack<T> {
public Stack(Class<T> clazz, int capacity) {
array = (T[])Array.newInstance(clazz, capacity);
}
private final T[] array;
}
But I really don't get what's going on. Can anyone help?
Source: (StackOverflow)
Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?
This is what I want to re-write:
foreach (Type t in this.GetType().Assembly.GetTypes())
if (t is IMyInterface)
; //do stuff
Source: (StackOverflow)
There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:
MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });
In this case, GetMethod()
will not return private methods. What BindingFlags
do I need to supply to GetMethod()
so that it can locate private methods?
Source: (StackOverflow)
I have a class with a private static final
field that, unfortunately, I need to change at run-time.
Using reflection I get this error: java.lang.IllegalAccessException: Can not set static final boolean field
Is there any way to change the value?
Field hack = WarpTransform2D.class.getDeclaredField("USE_HACK");
hack.setAccessible(true);
hack.set(null, true);
Source: (StackOverflow)
How can I achieve this?
public class GenericClass<T>
{
public Type getMyType()
{
//How do I return the type of T?
}
}
Everything I have tried so far always returns type Object
rather than the specific type used.
Source: (StackOverflow)
Does reflection in C#
offer a way to determine if some given System.Type
type models some interface?
public interface IMyInterface {}
public class MyType : IMyInterface {}
// should yield 'true'
typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface);
Source: (StackOverflow)
Is it possible to find all classes or interfaces in a given package? (Quickly looking at e.g. Package
, it would seem like no.)
Source: (StackOverflow)
Which of the following is better?
a instanceof B
or
B.class.isAssignableFrom(a.getClass())
The only difference that I know of is, when 'a' is null, the first returns false, while the second throws an exception. Other than that, do they always give the same result?
Source: (StackOverflow)
This has got me stumped. I was trying to optimize some tests for Noda Time, where we have some type initializer checking. I thought I'd find out whether a type has a type initializer (static constructor or static variables with initializers) before loading everything into a new AppDomain
. To my surprise, a small test of this threw NullReferenceException
- despite there being no null values in my code. It only throws the exception when compiled with no debug information.
Here's a short but complete program to demonstrate the problem:
using System;
class Test
{
static Test() {}
static void Main()
{
var cctor = typeof(Test).TypeInitializer;
Console.WriteLine("Got initializer? {0}", cctor != null);
}
}
And a transcript of compilation and output:
c:\Users\Jon\Test>csc Test.cs
Microsoft (R) Visual C# Compiler version 4.0.30319.17626
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.
c:\Users\Jon\Test>test
Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
at System.RuntimeType.GetConstructorImpl(BindingFlags bindingAttr, Binder bin
der, CallingConventions callConvention, Type[] types, ParameterModifier[] modifi
ers)
at Test.Main()
c:\Users\Jon\Test>csc /debug+ Test.cs
Microsoft (R) Visual C# Compiler version 4.0.30319.17626
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.
c:\Users\Jon\Test>test
Got initializer? True
Now you'll notice I'm using .NET 4.5 (the release candidate) - which may be relevant here. It's somewhat tricky for me to test it with the various other original frameworks (in particular "vanilla" .NET 4) but if anyone else has easy access to machines with other frameworks, I'd be interested in the results.
Other details:
- I'm on an x64 machine, but this problem occurs with both x86 and x64 assemblies
- It's the "debug-ness" of the calling code which makes a difference - even though in the test case above it's testing it on its own assembly, when I tried this against Noda Time I didn't have to recompile
NodaTime.dll
to see the differences - just Test.cs
which referred to it.
- Running the "broken" assembly on Mono 2.10.8 doesn't throw
Any ideas? Framework bug?
EDIT: Curiouser and curiouser. If you take out the Console.WriteLine
call:
using System;
class Test
{
static Test() {}
static void Main()
{
var cctor = typeof(Test).TypeInitializer;
}
}
It now only fails when compiled with csc /o- /debug-
. If you turn on optimizations, (/o+
) it works. But if you include the Console.WriteLine
call as per the original, both versions will fail.
Source: (StackOverflow)