vendredi 23 janvier 2015

Convert interface to its respecting map

For example if I have an interface{} value that originally a map[string]map[int64][]int64 or any other kind of map, how to get the key type of the map?



func Transverse(any interface{}) string {
res := ``
switch any.(type) {
case string:
return ``
case []byte:
return ``
case int, int64, int32:
return ``
case float32, float64:
return ``
case bool:
return ``
case map[int64]interface{}:
return ``
case map[string]interface{}:
return ``
case []interface{}:
return ``
default:
kind := reflect.TypeOf(any).Kind()
switch kind {
case reflect.Map:
// how to convert it to map[keyType]interface{} ?
}
return `` // handle other type
}
return ``
}





jeudi 22 janvier 2015

Implementing reflection mechanism in C++

So I'm trying to create a mechanism that would be similar to the Java reflection mechanism, making the language support 3 levels of abstraction, e.g: Creating 4 new classes: MetaClass, Object, Field, Method.


MetaClass is similar to "Class" class in Java, etc.


To give an example of I would expect it to work, take a look at this code:



class A{}
class B{}
MetaClass<A> A_class(NULL, "A") // bulding new class, super = NULL
MetaClass<B> B_class(&A_class, "B") // B_class inherits from A_class
A_class.addInstanceField("x", PUBLIC);
Object* a = A_class.newInstance();
cout << a->getFieldValue("x"); // prints 0, because default value of a field is 0 (and let's assume it will always be an int)
a->setFieldValue("x", 5);
cout << a->getFieldValue("x"); // prints 5.


I hope you get the idea. My problem is the design. this is how I defined MetaClass's fields:



std::list<Field>* fields;
std::list<Method>* methods;
MetaClass<T&>* superClass;
std::string className;
static bool instanceFlag = false;


and I'm having hard time figuring out how to implement the function that adds a field/method to the class, and how to know the difference between adding a static member or an instance member (I know what's the difference i just don't know how to design it well in my case)


e.g these functions are my problems:



void addInstanceMethod(std::string name, Modifier mod, Func func);

void addStaticMethod(std::string name, Modifier mod, Func func);

void addInstanceField(std::string name, Modifier mod);

void addStaticField(std::string name, Modifier mod);


plus, if you can help me with getting to unferstand this one as well it would be awsome:



virtual void invokeStaticMethod(std::string name);


hope my problem is clear.






Parsing XML - XDocument or Reflections

I have a huge XML(1000 lines) and I have 2 ways to parse through it and get the job done!. My job here is to extract some elements out of the XML and log it in the database. So, out of the following options, is which is better when deployed to Production and in terms of performance.


OPTION 1:



  1. Deserialise the XML using XMLDocument

  2. store only the node name in the database - to select which node to be retrieved.


OPTION 2:



  1. Deserialize the XML into a class object.

  2. Store the whole path of the XML node(including all the parent nodes) in the database.

  3. Use reflections to extract elements out of a class.


We are using C# as the language. Appreciate any response!. Thank You.






Dynamic table name in linq

I'm trying to execute some LINQ commands using a dynamic table name. For example, instead of



var o = (from x in context.users select x);


I want to use something like



var o = (from x in getTableObjectByName("users", context) select x);


More or less. Here's the code I have so far, which both compiles and runs:



using (MySiteEntities ipe2 = new MySiteEntities()) {
var propinfo1 = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
var propval1 = propinfo1.GetValue(ipe2, null);
}


That runs, but always returns zero records. The users table most definitely contains records, and in any case when I call it directly using the first method above I get all of the records as expected. How can I modify my code to actually pull down records, rather than just an empty collection?


Edit: I've also tried this:



using (MySiteEntities ipe = new MySiteEntities())
{
var prop = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
Type dbsetType = typeof(DbSet<>);
dbsetType = dbsetType.MakeGenericType(Type.GetType("MySiteNamespace.user"));

Type t = dbsetType.GetType();
var val = prop.GetValue(ipe, null);
}


In this case, the code not only runs, but actually returns the results as expected. However, val is an Object. I need to cast it to the type DbSet<user>, which would be easy enough, except that the parameter user is only known at runtime....the cast needs to be dynamic as well. I've tried using Convert.ChangeType(val, t);, but that throws an InvalidCastException (Object must implement IConvertible).


How can I convert the val variable to an actually usable object?


No idea if this is relevant, but this is on EntityFramework 4.






Reflection. Executing non-static method with parameters

I need to execute some method via reflection


method to execute



public void someMethod(int value1, int value2, String str, int value3)
{
try
{
// some code
}
catch (Exception e)
{
e.printStackTrace();
}
}


This is execution code



public static void execute()
{
try
{
String className = "some.class";
String classPath = "some.pack.name" + ":" + "some.class";
PathClassLoader loader = new dalvik.system.PathClassLoader(classPath, ClassLoader.getSystemClassLoader());

Class clazz = Class.forName(className, true, loader);
Method method = clazz.getDeclaredMethod("someMethod", Integer.class, Integer.class, String.class, Integer.class);
Object object = clazz.newInstance();

method.invoke(object, 1, 2, "str", 3);
}
catch (Throwable e) {e.printStackTrace();}
}


But I gets error



01-22 21:44:52.286: W/System.err(10877): java.lang.NoSuchMethodException: someMethod [class java.lang.Integer, class java.lang.Integer, class java.lang.String, class java.lang.Integer]
01-22 21:44:52.286: W/System.err(10877): at java.lang.Class.getConstructorOrMethod(Class.java:472)
01-22 21:44:52.286: W/System.err(10877): at java.lang.Class.getDeclaredMethod(Class.java:640)


What I'm doing wrong?






How do I check if a Scala HigherKinded TypeTag is an Array?

I'm trying to convert a type tag into a java class that maintains/persists normally-erased type parameters. There are quite a few libraries that benefit from conversions like these (such as Jackson, and Guice). I'm currently trying to migrate Manifest based code to TypeTag since Manifests are insufficient for some corner cases.


The JVM treats Arrays special in comparison to other data types. The difference between a classOf[Int] and classOf[Array[Int]] is that the method Class.isArray() will return true for the latter.


The Manifest implementation was simple. Manifest.erasure was a Class instance where isArray() was already valid/true.


The TypeTag implementation is trickier. There is no quick and easy erasure method. In fact the 'similar' TypeTag variant, RuntimeMirror.runtimeClass, prefers not to handle creating any Array based classes on our behalf. Read the documentation:



Note: If the Scala symbol is ArrayClass, a ClassNotFound exception is thrown because there is no unique Java class corresponding to a Scala generic array



To work around this I try to detect if it is an Array. If it is an array, then I manually create the class object. However, I've come across an additional edge case when Array has an unknown type argument.


First let me show you an example that is not a HigherKinded type.



import scala.reflect.runtime.universe._
class A[T]

val innerType = typeOf[A[Array[_]]].asInstanceOf[TypeRefApi].args.head
innerType <:< typeOf[Array[_]] // Returns true.


So far so good.



class B[T[_]]

val innerType = typeOf[B[Array]].asInstanceOf[TypeRefApi].args.head
innerType <:< typeOf[Array[_]] // Returns false.


I can't create a typeOf[Array] since it complains about the missing parameter. How can I detect that B has an type parameter of Array?


Also, what would the class instance look like in this case? Is it an Array[Object]?






Error when using Generic with Class?> parameter

Got some problem when using Generic with Enum:



enum MyEnum1 {
// ...
public static MyEnum fromString(String enumStr) { /* ... */ }
}

enum MyEnum2 {
// ...
public static MyEnum fromString(String enumStr) { /* ... */ }
}

enum MyEnum3 {
// ...
public static MyEnum fromString(String enumStr) { /* ... */ }
}

class MyClass {
Map<Class<? extends Enum<?>, EnumSet<? extends Enum<?>>> map;

public <E extends Enum<E>> void addValue2EnumSet(Class<E> enumType, E value);

// enumType and valueStr is of the same length
public static Map<Class<? extends Enum<?>, EnumSet<? extends Enum<?>>> getMapOfEnumSet(Class<? extends Enum<?>>[] enumTypes, String[] valueStrs) {
for (int i = 0; i < enumTypes.length; ++i) {
// for each enumType and valueStr pair
// add the value from valueStr to the Map
Class<? extends Enum<?>> enumType = enumTypes[i];
String valueStr = valueStrs[i];
MyClass c = // ...
Method fromStringMethod = enumType.getDeclaredMethod("fromString", String.class);
c.addValue2EnumSet(enumType, enumType.cast(fromStringMethod.invoke(null, valueStr))); // error!
}
return c.map;
}
}


In this line c.addValue2EnumSet(enumType, enumType(fromStringMethod.invoke(null, valueStr)));, an compile-error is the second parameter, Found: 'java.lang.Enum<?>, required: '? extends java.lang.Enum'`


How to call addValue2EnumSet() in getEnumSetOf()?


In this case, a Class<? extends Enum<?> enumType parameter is passed, and it is used to judge which kind of Enum (Enum1/2/3) is the target, then call the fromString() method to generate the corresponding Enum instance. I have no idea but the reflection to get methods from the enumType.