How does one instantiate an array of maps in Java?

Not strictly an answer to your question, but have you considered using a List instead? List<Map<String,Integer>> maps = new ArrayList<Map<String,Integer>>(); … maps.add(new HashMap<String,Integer>()); seems to work just fine. See Java theory and practice: Generics gotchas for a detailed explanation of why mixing arrays with generics is discouraged. Update: As mentioned by Drew in the comments, … Read more

Instantiate a class from its textual name

Here’s what the method may look like: private static object MagicallyCreateInstance(string className) { var assembly = Assembly.GetExecutingAssembly(); var type = assembly.GetTypes() .First(t => t.Name == className); return Activator.CreateInstance(type); } The code above assumes that: you are looking for a class that is in the currently executing assembly (this can be adjusted – just change assembly … Read more

Determine if a type is static

static classes are declared abstract and sealed at the IL level. So, you can check IsAbstract property to handle both abstract classes and static classes in one go (for your use case). However, abstract classes are not the only types you can’t instantiate directly. You should check for things like interfaces (without the CoClass attribute) … Read more

Creating instance of type without default constructor in C# using reflection

I originally posted this answer here, but here is a reprint since this isn’t the exact same question but has the same answer: FormatterServices.GetUninitializedObject() will create an instance without calling a constructor. I found this class by using Reflector and digging through some of the core .Net serialization classes. I tested it using the sample … Read more

Why is Class.newInstance() “evil”?

The Java API documentation explains why (http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()): Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The Constructor.newInstance method avoids this problem by wrapping any exception thrown by the constructor … Read more

Swift: Creating an Array with a Default Value of distinct object instances

Classes are reference types, therefore – as you noticed – all array elements in var users = [User](count: howManyUsers, repeatedValue:User(thinkTime: 10.0)) reference the same object instance (which is created first and then passed as an argument to the array initializer). For a struct type you would get a different result. A possible solution: var users = … Read more