jeudi 31 décembre 2015

java.lang.ClassCastException: com.sun.proxy.$Proxy47 cannot be cast to

I am running a test under Arquillian OSGi with this code:

An annotation:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Size {
    int min() default 0;

    int max() default 2147483647;
}

This class

public class FooEntity {
    @Size(min = 0, max = 100)
    public int number;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }
}

And a validation method somewhere else:

@Override
public List<String> validateEntity(Object entity) throws IllegalAccessException {
    List<String> list = new ArrayList<>();
    for(Field field  : entity.getClass().getDeclaredFields()) {
        for (Annotation annotation : field.getDeclaredAnnotations()) {
            if (annotation.annotationType().getName().equals(Size.class.getName())) {
                Size size = (Size) annotation; // --> Throws 'ClassCastException' exception!!
                int value = field.getInt(entity);
                if (value < size.min() || value > size.max())
                    list.add("Error Message: Invalid size.");
            }
        }
    }
    return list;
}

When I debug this part of the code, I place this same line in the 'watch' window of the IDE and it shows the code is correct, I mean, it returns annotation as Size type, but during run-time the code just breaks. Does anybody knows why is this cast not working? And why is this annotation working under a Proxy class?

Here is the StackTrace of the exception:

java.lang.ClassCastException: com.sun.proxy.$Proxy47 cannot be cast to persistence.ext.annotation.Size
    at persistence.ext.internal.PersistenceImpl.validateEntity(PersistenceImpl.java:144)
    at integration.PersistenceExtTest.ValidateSizeAnnotation(PersistenceExtTest.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.jboss.arquillian.junit.Arquillian$8$1.invoke(Arquillian.java:370)
    at org.jboss.arquillian.container.test.impl.execution.LocalTestExecuter.execute(LocalTestExecuter.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116)
    at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67)
    at org.jboss.arquillian.container.test.impl.execution.ContainerTestExecuter.execute(ContainerTestExecuter.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:92)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.test.impl.TestContextHandler.createTestContext(TestContextHandler.java:130)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:73)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
    at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.test(EventTestRunnerAdaptor.java:136)
    at org.jboss.arquillian.junit.Arquillian$8.evaluate(Arquillian.java:363)
    at org.jboss.arquillian.junit.Arquillian$4.evaluate(Arquillian.java:245)
    at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:422)
    at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
    at org.jboss.arquillian.junit.Arquillian$5.evaluate(Arquillian.java:259)
    at org.jboss.arquillian.junit.Arquillian$7$1.invoke(Arquillian.java:315)
    at org.jboss.arquillian.container.test.impl.execution.BeforeLifecycleEventExecuter.on(BeforeLifecycleEventExecuter.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:92)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.test.impl.TestContextHandler.createTestContext(TestContextHandler.java:130)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:73)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116)
    at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.fireCustomLifecycle(EventTestRunnerAdaptor.java:159)
    at org.jboss.arquillian.junit.Arquillian$7.evaluate(Arquillian.java:311)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:204)
    at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:422)
    at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
    at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:218)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:166)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
    at org.jboss.arquillian.junit.container.JUnitTestRunner.execute(JUnitTestRunner.java:66)
    at org.jboss.arquillian.osgi.JUnitBundleTestRunner.execute(JUnitBundleTestRunner.java:51)
    at org.jboss.arquillian.protocol.jmx.JMXTestRunner.doRunTestMethod(JMXTestRunner.java:180)
    at org.jboss.arquillian.protocol.jmx.JMXTestRunner.runTestMethodInternal(JMXTestRunner.java:162)
    at org.jboss.arquillian.protocol.jmx.JMXTestRunner.runTestMethod(JMXTestRunner.java:120)
    at org.jboss.arquillian.osgi.ArquillianBundleActivator$2.runTestMethod(ArquillianBundleActivator.java:111)
    at org.jboss.arquillian.protocol.jmx.JMXTestRunner.runTestMethod(JMXTestRunner.java:137)
    at org.jboss.arquillian.osgi.ArquillianBundleActivator$2.runTestMethod(ArquillianBundleActivator.java:124)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at com.sun.jmx.mbeanserver.StandardMBeanIntrospector.invokeM2(StandardMBeanIntrospector.java:112)
    at com.sun.jmx.mbeanserver.StandardMBeanIntrospector.invokeM2(StandardMBeanIntrospector.java:46)
    at com.sun.jmx.mbeanserver.MBeanIntrospector.invokeM(MBeanIntrospector.java:237)
    at com.sun.jmx.mbeanserver.PerInterface.invoke(PerInterface.java:138)
    at com.sun.jmx.mbeanserver.MBeanSupport.invoke(MBeanSupport.java:252)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at javax.management.MBeanServerInvocationHandler.invoke(MBeanServerInvocationHandler.java:298)
    at com.sun.proxy.$Proxy27.runTestMethod(Unknown Source)
    at org.jboss.arquillian.protocol.jmx.JMXMethodExecutor.invoke(JMXMethodExecutor.java:80)
    at org.jboss.arquillian.container.test.impl.execution.RemoteTestExecuter.execute(RemoteTestExecuter.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:116)
    at org.jboss.arquillian.core.impl.EventImpl.fire(EventImpl.java:67)
    at org.jboss.arquillian.container.test.impl.execution.ClientTestExecuter.execute(ClientTestExecuter.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.invokeObservers(EventContextImpl.java:99)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:81)
    at org.jboss.arquillian.container.test.impl.client.ContainerEventController.createContext(ContainerEventController.java:142)
    at org.jboss.arquillian.container.test.impl.client.ContainerEventController.createTestContext(ContainerEventController.java:129)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.test.impl.TestContextHandler.createClassContext(TestContextHandler.java:92)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.test.impl.TestContextHandler.createTestContext(TestContextHandler.java:130)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.test.impl.TestContextHandler.createSuiteContext(TestContextHandler.java:73)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.jboss.arquillian.core.impl.ObserverImpl.invoke(ObserverImpl.java:94)
    at org.jboss.arquillian.core.impl.EventContextImpl.proceed(EventContextImpl.java:88)
    at org.jboss.arquillian.core.impl.ManagerImpl.fire(ManagerImpl.java:145)
    at org.jboss.arquillian.test.impl.EventTestRunnerAdaptor.test(EventTestRunnerAdaptor.java:136)
    at org.jboss.arquillian.junit.Arquillian$8.evaluate(Arquillian.java:363)
    at org.jboss.arquillian.junit.Arquillian$4.evaluate(Arquillian.java:245)
    at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:422)
    at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
    at org.jboss.arquillian.junit.Arquillian$5.evaluate(Arquillian.java:259)
    at org.jboss.arquillian.junit.Arquillian$7.evaluate(Arquillian.java:321)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.jboss.arquillian.junit.Arquillian$2.evaluate(Arquillian.java:204)
    at org.jboss.arquillian.junit.Arquillian.multiExecute(Arquillian.java:422)
    at org.jboss.arquillian.junit.Arquillian.access$200(Arquillian.java:54)
    at org.jboss.arquillian.junit.Arquillian$3.evaluate(Arquillian.java:218)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.jboss.arquillian.junit.Arquillian.run(Arquillian.java:166)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)





Get inner attribute class value with class.name String

Let's say this case

class A {
    int bla;
    B B;
}

class B {
    public int foo;
}

And I have an array {"B.foo", "bla"}. Now getting the Class A and without any idea about his internal structure how can I use reflection, or another third party, to extract the values of those attributes that I have on my array.

Of course I know reflection and how get an attribute in the first class level(A.bla), but If I want to get get B.foo without add any business logic how can I get that value from A just using the String Class-attribute?





Android change value of method to check against button ID

I am trying to make a method to iterate over a set of buttons and up the count of they meet the correct condition. In doing so I want to know if it is possible to increment the value of methods such as R.id.gridButton method based on the value of the counter using regex or if that is not possible, would reflection would be the correct way to go about it.

Example: i == 1 R.id.gridButton1

i == 2 R.id.gridButton2

public int getBoardSize() {
        int buttonCount = 0;
        TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
        System.out.println("Table child count: " + tableLayout.getChildCount());

        for (int rowIndex = 0; rowIndex < tableLayout.getChildCount(); rowIndex++) {
            View tableLayoutChild = tableLayout.getChildAt(rowIndex);
            if (tableLayoutChild instanceof TableRow) {
                for (int i = 0; i < ((ViewGroup) tableLayoutChild).getChildCount(); i++) {
                    System.out.println("Value of i: " + i);
                    View view = ((ViewGroup) tableLayoutChild).getChildAt(i);
                    if (view instanceof Button && view.getId() == R.id.gridButton1 ) {
                        buttonCount++;
                    }
                }
            }
        }
        System.out.println("Child count: " + buttonCount);
        return buttonCount;
    }





reflection woes utilizing generalized lambda with parameter from this pointer

I have 3 compilers disagreeing on the below C++14 code:

#include <type_traits>

template <typename P, typename F>
constexpr auto can_call(P* p, F&& f) -> decltype(f(p),std::true_type{}) { return {}; }

template <typename F>
constexpr std::false type can_call(void const*, F&&) { return {}; }

struct C {
  C() { auto pc = can_call(this, [&](auto p) -> decltype(p->f(3)) {}); }
  void f(int);
};

template <typename T>
struct CT {
  CT() { auto ptc = can_call(this, [&](auto p) -> decltype(p->f(3)) {}); }
  void f(T);
};

int main()
{
  C oc;
  auto pc = can_call(&oc, [&](auto p) -> decltype(p->f(3)) {});
  CT<int> oct;
  auto ptc = can_call(&oct, [&](auto p) -> decltype(p->f(3)) {});
}

clang++ 3.7 accepts it without a hitch.

g++ 4.9, 5.1, 5.2, 5.3 and trunk fail the CT<T> constructor, with the message:

t.cpp: In instantiation of ‘CT<T>::CT() [with T = int]’:
t.cpp:24:11:   required from here
t.cpp:16:61: error: base operand of ‘->’ has non-pointer type ‘auto:2’
     CT() { auto ptc = can_call(this, [&](auto p) -> decltype(p->f(3)) {}); }
                                                              ^

VisualStudio 2015 Community is the exact opposite of g++ and fails all lambdas, except the templated CT<T> constructor, complaining that left of '->f' must be a pointer. (I have not checked if perhaps it wrongly gets the std::false_type result in the CT<T> constructor.)

From this I have two questions:

  1. What is expected? I have tried to read the (draft C++17) standard from github, but to be honest I don't even know where to look, especially since the compilers disagrees a bit too much.
  2. Can the intended reflection be portably implemented in a different way? I want (not need) the functionality to improve compilation error messages from a library.




mercredi 30 décembre 2015

System.Reflection.Emit - If Statement Generation

Good evening!

I've been having some issues with my program for the last few days, I'm trying to learn how If statements are generated with ILGenerator in C#.

Here's my code: (ilg is an ILGenerator)

    ilg.Emit(OpCodes.Ldc_I4_1);
    Label start = ilg.DefineLabel();
    ilg.Emit(OpCodes.Brfalse, start);
    ilg.Emit(OpCodes.Ldstr, "Hello");
    ilg.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
    ilg.MarkLabel(start);

Some notes:

  • Alone, calling Console.WriteLine works perfectly.
  • This is the error that I get when I run the generated exe:

    "Unhandled Exception: System.InvalidProgramException: Common Language Runtime detected an invalid program." at Testing.Test.Main(String[] )
    
    

Thanks!





Java Interface Derived From Class?

I'm working on an Android framework (http://ift.tt/1QZATJW) which takes data model classes and uses reflection to update views when they are created or updated. I use a dynamic proxy factory for this, and I currently have the user enter both the real object and an interface that specifies any state changing methods. My question is, is there a way the code could auto generate an interface from the class? It would look something like this.

Class<?> derivedInterface = somehowGetAnInterface(Original.class)

Where original is an instance something like:

public class Original {
    String someData;

    public void setSomeData(String s) {
        someData = s;
    }

    public String getSomeData() {
        return someData();
    }
}

And derived interface gets created either at compile time or run time but looks something like this:

public interface OriginalInterface {
    public void setSomeData(String s);
    public String getSomeData();
}





How to compile & instantiate a Java class from source which has project dependencies?

This is great, but what if the class in the uncompiled source should inherit from a project specific class (which is already loaded), and has other project dependencies?





Method for finding an attribute by string name

I am still very new to C#, (I come from a Python background ).

What I am trying to do is create a function that can return a value in from its object.

Here is what I have so far.

public class Base
{
    public string thing = "Thing";
    public T GetAttribute<T>(string _name)
    {
        return (T)typeof(T).GetProperty(_name).GetValue(this, null);
    }
}

What I would ideally like is to call:

string thingy = GetAttribute<string>("thing");

but I have a feeling I got the wrong end of the stick when reading up on this because I keep getting null reference exceptions.

I do apologise if this is a duplicate question; I have read a lot of other peoples Q&As and I can't seem to make it work for me. Any help, however vague, is much appreciated.





Get all the classes that implments a trait in Scala using reflection

I want to list out all the case classes which implements a particular trait. I am currently using Clapper ClassUtil for doing that. I am able to get the case classes that are directly implementing a trait. However, I am not able to get the other classes which are not directly implementing the trait. How can I get all classes which directly or indirectly implements a trait. ?

val finder = ClassFinder()
finder.getClasses().filter(_.isConcrete).filter(_.implements("com.myapp.MyTrait"))

Scala Version : 2.11

Clapper Class Util Version : 1.0.6

Is there any other way I can get these information? Can someone point me to the right direction? I tried using scala.reflect but could not understand how to get the info.





Invoke mirrored global function

I'm searching all global annotated functions in my lib:

@MyAnnotation()
String func(arg1, arg2) => "test";

main() {
    var routines = m.currentMirrorSystem().findLibrary(#my.lib).declarations.values
      .where((m.DeclarationMirror dm) =>
        dm is m.MethodMirror && dm.metadata.map((m.InstanceMirror im) => im.reflectee)
            .any((refl) => refl is MyAnnotation)
      );
     // this works all ok

Now I have List<DeclarationMirror> of my annotated functions. But I need to invoke it later. ClosureMirror has invoke method, but I cannot see any way to get this for my either MethodMirror or Symbol of routine. I cannot use just new ClosureMirror(func) as I have dozens of my annotated functions and I don't know every name. Also I dont have any ClassMirror or InstanceMirror.

So question is, how to invoke global mirrored functions by its Symbol or MethodMirror.





How to make a routine deal with observable collection of instances of a generic class

I want to make a logger (in a library) that iterates through every field of whatever class and sets all values in a comma separated values line. It's input value is a observable collection of whatever class. To make it generic I made it

ObservableCollection newObcObject.

public static bool WriteLog_Reflection(string fileName, long maxLogSizeMB, ObservableCollection<object>newObcObject, out string strError)
{
  try
  {
    strError = string.Empty;
    string lines = string.Empty;
    foreach (var item in newObcObject)
    {
      foreach (var prop in item.GetType().GetProperties())
      {
        //string str = prop.Name + " = " + prop.GetValue(item, null).ToString();
        lines += prop.GetValue(item, null).ToString() + "; ";
      }
    }

    return true;
  }
  catch (Exception exc)
  {
    strError = exc.ToString();
    return false;
  }
}

and this works..

The problem now is how to convert a specific observable collection to an object observable collection.

E.g. ObservableCollection ------> ObservableCollection

This is my solution but I'm open to whatever other solutions. thanx





mardi 29 décembre 2015

How to invoke method which accepts parameter of type base class using reflection?

I have classes like below

public Class A
{    
    protected A()
    {
    }
}

Public class B : A
{
    public B()
    {
    }
}

I have method like below

public class C{
    private void Method1(A obj)
    {
    }
}

method call using reflection

MethodInfo method1= typeof(C).GetMethod("Method1", BindingFlags.NonPublic | BindingFlags.Instance);

var result = method1.Invoke(cObject, new object[] { objectB });

I am trying to call this private method using reflection but I am getting Argument exception

An exception of type 'System.ArgumentException' occurred in mscorlib.dll but was not handled in user code

Object of type 'B' cannot be converted to type 'A'.

Could any one advise me in this?





How to get namespace, class, methods and its arguments with Reflection

I need to load the dll using reflection and have to get the namespace, class, methods and its arguments for that dll. Also, I need to write those information in a log file.

I have used the following code. But I got only up to class that has been written to log file.

Assembly dll = Assembly.LoadFile(@"D:\Assemblies\Myapplication.dll");
foreach (Type type in dll.GetTypes())
{
    var name = "Myapplication~" + type.FullName;
    File.AppendAllText("Assembly Details.log", "Myapplication~" + type.FullName + "\r\n\r\n");

    Console.WriteLine(type.FullName);
}

In the log file, the information needs to written as below.

Myapplication~namespace.class~method(arguments)

Eg:

Myapplication~copyassembly.class~Mymethod(String, Type)

Any suggestions would be greatly helpful.





Setting a generic parameter of a class through reflection?

So before I ask the question, I feel that I must explain my situation for the question to make any logical sense:

I have the generic nested class ThreadHierarchy<P,C extends ExtendedThreadHandler<T>> (where P represents the parent and C, the child) inside of the generic class ExtendedThreadHandler<T> (where T represents type), and I need to create an instance of the TheradHierarechy class in the main constructor of its superclass like so:

    //Thread State initializer
public ExtendedThreadHandler() {
    this.setThreadClass((T)this);
    this.setThreadName(getClassInstance().getClass().getSimpleName());
    ThreadHierarchy th = new ThreadHierarchy<Thread.currentThread().getClass(), T>(true);
}

The issue with this is that while instantiating classes, the generic input values only accept string literals such as the predefined generic type T from ExtendedTheadHandler<T>, and therefore, I cannot input a method call or variable into the instance parameters.

Is there a way to either:

A) Input return values, in this case a class, into a generic class or method by defining a new instance variable to pass in? (I couldn't figure out how to do this)

OR

B) Use reflection to create an instance of the class where the values of P and C can be assigned manually?





C#: Getting Names of properties in a chain from NewExpression members

Suppose this expression:

Expression<Func<DateTime, dynamic>> exp = dt => new { dt.Second, dt.Hour, dt.Date.Day };

I need to obtain the following: "Second", "Hour", "Date.Day"

The best I've been able to accomplish is the following:

var body = exp.Body as NewExpression;
foreach(var member in body.Members)
    member.Name().Dump();

But I only get: "Second", "Hour", "Day"


This is somewhat similar to this question but I'm dealing with a NewExpression here.





Get the type and value of Sub Class where you only have Sub Class name as a string

I'm trying to assemble a generic method which is passed an object of a class type (ie: dbJob) and also the name of a sub class like 'LastUpdatedDate' and a process string, which can be '> 01-01-2015'.

The method looks like this

public bool checkProcess(object obj, string className, string processStr)
{
    PropertyInfo[] propertyInfo;
    bool returnValue = false;
    propertyInfo = obj.GetType().GetProperties();
    for (int i = 0; i < propertyInfo.Length; i++)
    {
        if (propertyInfo[i].Name == propName)
        {
            var objType = propertyInfo[i].GetType();
            var objValue = propertyInfo[i].GetValue(this, null);
            returnValue = qualifyClass(objType, objValue);
            if (!returnValue)
            {
                break;
            }
        }
    }
    //propertyInfo className evaluate processStr
    return returnValue; 
} 

When the method runs, objectType just holds {System.Type{System.RuntimeType}} and objValue crashes saying 'Object is not of the same type'. I just need the type and value of the Sub Class that matches propName, where am I going wrong?





How to use reflect to instant a GENERIC class in JAVA?

I wanna instant a generic class, like SomeContainer<SomeClass>. I just have the className, so, use java reflect, like Class.forNameClass.forName(param).newInstance(); but it doesn't support generic, how can I do ?





Scala instance-of on typed parameter with TypeTag?

Can I implement the following method:

// returns weather `v` is instance of `A`
def isItOfType[A](v: Any) = ???

With TypeTag?
Or do I have to use ClassTag (classsTag[A].runtimeClass.isInstance(v))?





lundi 28 décembre 2015

Using reflection to invoke Type parameterized methods

The google cloud dataflow sdk has a class that registers Coders for different Avro types.

CoderRegistry cr = p.getCoderRegistry();
cr.registerStandardCoders();
cr.registerCoder(Row.class, AvroCoder.of(Row.class));
cr.registerCoder(Destination.class, AvroCoder.of(Destination.class));
cr.registerCoder(Device.class, AvroCoder.of(Device.class));
cr.registerCoder(Location.class, AvroCoder.of(Location.class));
cr.registerCoder(Source.class, AvroCoder.of(Source.class));
cr.registerCoder(DimensionalMetric.class, AvroCoder.of(DimensionalMetric.class));
cr.registerCoder(DimensionSet.class, AvroCoder.of(DimensionSet.class));
cr.registerCoder(MetricSet.class, AvroCoder.of(MetricSet.class));

But as you can imagine this gets pretty cumbersome and I would like to use java reflection API to automatically register all classes in the package com.brightcove.rna.model. I imagine this would look something like this:

void registerAllModels(Pipeline p) {
    CoderRegistry cr = p.getCoderRegistry();
    Reflections r = new Reflections("com.brightcove.rna.model");
    Set<Class<? extends IndexedRecord>> classes = r.getSubTypesOf(IndexedRecord.class);
    for (Class<? extends IndexedRecord> clazz : classes) {
        cr.registerCoder(clazz, AvroCoder.of(clazz));
    }
}

Unfortunately, this doesn't work. What am I doing wrong here?





Is there a way to tell if a method is an event or property accessor?

That is, without enumerating all the PropertyInfos in the containing type. Does the compiler apply some information to these methods that would allow me to know when my MethodInfo is one?





Scala pattern match on classes with a typed paremeter

I'm trying to pattern match on a custom class with a typed parameter:

class Foo[A]

def isMyFoo[A: ClassTag](v: Any) = v match {
    case mine: Foo[A] => "my foo"
    case other: Foo[_] => "not my foo"
    case _ => "not a foo"
}

That will not work; no matter the type of Foo, I will always get "my foo".

The only way I was able to make something like this work, is this:

class Foo[A](implicit t: ClassTag[A]) {
    val tag = t
}

def isMyFoo[A: ClassTag](v: Any) = v match {
    case foo: Foo[_] =>
        if (foo.tag == classTag[A]) "my foo"
        else "not my foo"
    case _ => "not a foo"
}

Is there a more elegant way of doing so? Do I have to keep the ClassTag inside Foo?





Scala pattern matching on generic type with TypeTag generates a warning while ClassTag not?

I have two very similar methods. The only difference is the use of ClassTag and TypeTag:

def matchClass[A: ClassTag](v: Any) =
    v match {
        case a: A => "it's A"
        case _ => "not A"
    }

def matchType[A: TypeTag](v: Any) = ... // same code as matchClass

A compile warning will show for matchType, but not for matchClass:
abstract type pattern A is unchecked since it is eliminated by erasure case a: A

Why is there a warning? why does it show only for TypeTag and not ClassTag?





Set indexed value by reflection gives me TargetParameterCountException

I have a PolygonRenderer class containing a Vertices property, which is a List, holding the points of the polygon the class renders.

When I try to change a specific point in this list by reflection, I get a System.Reflection.TargetParameterCountException on the last line of my function :

    public override void ApplyValue(string property, object value, int? index)
    {
        List<PropertyInfo> properties = Data.GetType().GetProperties().ToList();
        PropertyInfo pi = properties.FirstOrDefault(p => p.Name == property);
        pi.SetValue(Data, value,
            index.HasValue ? new object[] { index.Value } : null);
    }

When I debug, I get index.Value = 3, Data is the PolygonRenderer instance and pi reflects the Vertices property, which count = 4.

Since my index is supposed to be the last item of my list, how is it possible that I get a count exception on that property ?

Thanks





Why Java's String is not assignable from Comparable interface

Javadoc says that String implements Comparable<String>

But, the following code returns false:

String.class.isAssignableFrom(Comparable.class)

How to check if some class implements given interface (in Spring environment)?





dimanche 27 décembre 2015

How can I dynamically generate and populate a multi-dimensional array in C#

I'm working on a serializer and have run into a real wall with multi-dimensional arrays. If I use Activator.CreateInstance() it creates a one dimensional array just fine, but it fails to work when used as follows:

var indices = new[] { 2, 2 };
Type type = typeof(int[,]);
var result = Activator.CreateInstance(type, indices) as Array;

If I instead use Array.CreateInstance() to generate my array, it works for single and multi-dimensional arrays alike. However, all my calls to the SetValue() method on the array, which I use to dynamically set values, generates an exception, whereas it works fine on the single dimensional arrays I created using Activator.CreateInstance(). I'm really struggling to find a viable solution that allows me to dynamically create an array of any dimension/size and then populate the array with values. I'm hoping someone with more reflection experience can shed some light on this.

When trying to create a multi-dimensional array with Activator I get the exception:

Constructor on type 'System.Int32[,]' not found.

When I instead use Array.CreateInstance() and then call SetValue() I get the following exception from the SetValue() call:

Object cannot be stored in an array of this type.

Which frankly makes no sense to me since the value is an int and the array is an int[,].





Java Reflection Method Listener

I'm using reflection to execute plugins which is fine but i want to add like a proxy so everytime the sendMessage method is called from my plugin it does something from the main application.

    case "execute":
        String url = command.getArguments()[1];
        URL u = new URL("jar", "", url + "!/");
        URLClassLoader ucl = new URLClassLoader(new URL[] { u });
        Class<?> c = ucl.loadClass("com.j.Plugin");
        Object instance = c.newInstance();
        Method m = c.getMethod("execute", String.class, String[].class);
        m.invoke(instance, Constants.USER_ID, Arrays.copyOfRange(command.getArguments(), 1, command.getArguments().length));            
        //Upon sendMessage method get message here???
        break;
    }

This method executes the plugin which is fine.

package com.j;

public class Plugin {

    public void execute(String userId, String[] args) {
        System.out.println(1);
        sendMessage("2");
    }

    public void sendMessage(String message) {
        System.out.println(message);
    }

}

But i want it so everytime sendMessage is called i get what the message is under m.invoke()





Reflection on CLR C++ code with dotPeek

I have this code written in CLR c++ :

namespace NS{
public class B {
public:
    B()
    {
        int k = 1 + 1;
    }
    static int K;
    int getId()
    {
        return 0;
    }
    static double getId2()
    {
        return 0;
    }
};
}

I compile it to dll and use DotPeek and I am getting this result :

namespace NS
{
[CLSCompliant(false)]
[NativeCppClass]}
[StructLayout(LayoutKind.Sequential, Size = 1)]
public struct B
{
}
}

And also using C# reflection like this :

var module = Assembly.Load("MyCLRCPP").Modules.First();
foreach (var data in module.GetFields())
{
  Debug.WriteLine(data.Name);
 }

I get only some gibberish :

__unep@?DoNothing@DefaultDomain@@@$$FCGJPAX@Z __unep@?_UninitializeDefaultDomain@LanguageSupport@@@$$FCGJPAX@Z

My question is : Why there is no code there?





Invoke methods with params

I've got an editor, which reflects methods in a script (and its parameters) and then making them all viewable by the user, making it easy for the end user to invoke methods from the editor.

Example methods would be:

public void TestMethodOne(damage float1, duration float2, ticks float3){}
public void TestMethodTwo(damage float1, walkSpeed float2){}

which in the editor would look like:

TestMethodOne - Damage:[]  Duration:[]   Ticks:[]
TestMethodTwo - Damage:[]  WalkSpeed:[]                   //with [] being user input window

The name of the methods that the use wishes to use are stored as strings, and the parameters are stored in float Lists.

Now I would like to run these methods with the stored variables, without changing their parameters.

Below works if you change them....:

 MethodInfo method = typeof(MethodHolderScript).GetMethod(storedMethodName);
 string[] values = floatParameterList.ToArray();
 object[] args = { values };
 methodName.Invoke(instance, args);

But then I have change the parameters of all of the methods to example:

    public void TestMethodOne(object[] args){}
    public void TestMethodTwo(object[] args){}

Which is not what I want to do. The number of methods and the amount of its float parameters will be updated regularly, and the editor is coded to display the methods values based on its parameter names, so the above "fix" is not an option.

Is there any way to make this work, work around or perhaps another way other than reflection to achieve this?





How do I read the version number of file inside zip archive?

I have a zip file that contains an exe, and I want to get the version number of the exe file without having to extract it physically.

I know how to read the contents of a zip file, and have code that will read a text file in it, but I can't find out how to get the version of an exe.

Anyone?





Confirmation on my Understanding of Beginning Android Concept (Using Multiple Activities)

I am a beginner at android development, and have reached the end of Building your First App. Before I move on, I would like to confirm and validate my understanding of using multiple activities and communicating from one activity to another.

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

1) Is my understanding correct that the second paramater in the constructor for Intent (Intent intent = new Intent(this, DisplayMessageActivity.class)) serves as a reference for startActivity(...) and reflection is used to call the method onCreate() in the class DisplayMessageActivity since the class DisplayMessageActivity was given as a class object?

2) What is the use of the first paramater (the context one in the constructor)? (Basically how does Android use the first parameter, a brief description please, to start the activity)?

3) As seen in the tutorial, last part of building your first app, it advises me to declare a variable as such: (public final static String EXTRA_MESSAGE = "me.marshac.myfirstapp.MESSAGE";). I know the purpose of this declaration and initialization, but why don't I have to specify the full package name (me.marshac.myfirstapp. (...) .MESSAGE) and where is the MESSAGE variable coming from? The only two variables similar to that are both local variables in sendMessage() and the other activity's onCreate(), but they are different case and local?

I am sorry for the very in-depth inquiries, I want to establish a firm understanding of the beginner concepts before I move on to intermediate/advanced ones.





Varargs-Constructor cannot act as default constructor using reflection

FXML-View:

....
    <GridPane...>
        <PersonController... />
    </GridPane...>
....

Class PersonController:

public PersonController(Person... personsToExclude) {
    FXMLLoader.load("PersonControllerView.fxml")
    this.personsToExclude = personsToExclude;
}

This code sample leads to an excpetion, because the class cannot be invoked without a default constructor (by the FXMLLoader). Now my question: You CAN use this constructor as default constructor. You can create such an object like this:

PersonConstructor pc = new PersonConstructor(); // This calls the upper constructor

Why isn't reflection able to use this constructor too? Varargs appear to be arrays internally which will be null by default if no parameter was handed over.

Was this design decision solely made to reduce complexity (it actually does reduce it a little bit for the reader) or are there any other reasons why it is important to still have a "real" default constructor?





samedi 26 décembre 2015

Get enum.values() from class that containing it

class Clazz{
    public enum MyEnum{
        Hello, World
    }
}

With class Clazz, how do I get MyEnum.values()?

An example of the usage is:

Class unknownClass = getSomeClass();

How to get MyEnum.values() from unknownClass?





how to refer to instance method

I want to know ways to get reference to an instance method in Java 7

public class MyClass{
    public void myMethod(){
        ....
    }
}

I know I can do this

MyClass.class.getMethod(methodName);

but this technique is prone to error since it relies on String input (i.e. when method name is changed, etc). Is there a more reliable way to refer to a method?

Thanks





Cannot invoke an internal method within a dll

I have this class in a ddl file:

namespace A
{
    internal class PW
    {
        static PW()
        {
            //code
        }

        internal static string G(int num)
        {
            //more code
        }
    }
}

However, when I call this:

typeof(PW).GetMethod("G", BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { typeof(String) }, null);

I get null.

The dll file is referenced in the project and PW class is found.

I know I cannot invoke it with

A.PW.G(0);

But I will get cannot access internal class/method error which at least proves that the program is aware of its existence.

How do I call the G method?





Find Generic Type at Runtime Java

I wrote some code the looks like this:

public class A<T> {
    public Type getGenericType() {
        // should return the type of T at runtime
    }
}

meaning, the call:

A<Integer> a = new A<>();
a.getGeneicType();

should return Integer.

Is it possible in Java?





how to access sub class properties of object.GetType() when only have the name of the sub class as a string

I'm trying to assemble a generic method which is passed an object of a class type (ie: dbJob) and also the name of a sub class like 'LastUpdatedDate' and a process string, which can be '> 01-01-2015'.

The method looks like this

public bool checkProcess(object obj, string className, string processStr)
{
    PropertyInfo[] propertyInfo;
    bool returnValue = false;
    propertyInfo = obj.GetType().GetProperties();
    //propertyInfo className evaluate processStr
    return returnValue; 
} 

I'm using Reflection to get the property information for my Class. Say I'm passing dbJob, how can I use the string say 'LastUpdatedDate' for the sub class to get me the properties to evaluate processStr?





How do I perform a bitwise OR on .NET enums in script running with NLua?

I have the following reflection code in C# which I'm trying to replicate using NLua script: G.Object.GetType().GetField("count", BindingFlags.Instance | BindingFlags.NonPublic);

Everything is fine, until I try to use Bitwise OR operation on two flags. I have alerady tried:
BindingFlags.Instance + BindingFlags.NonPublic (arithmetic operation on non-number) BindingFlags.Instance | BindingFLags.NonPublic (not working, obviously, but worth a try)

I have also tried pure Lua implementations of bit-manipulation libraries. All fail, because what I'm trying to OR is called 'userdata' type in NLua.

Conversion of 'userdata' type using tonumber() also fails.

My current Lua code is below:
obj = G.Object:GetType() field = obj:GetField("count", *...two OR'd flags here...*)





using reflection methods in traits

I have 15 Entity Classes, and I want to put getEntityName static function in there but I don't want to make code duplication, and some of my entities extends vendor related class so I cannot put an abstract class to extend from these entities. I wanted to use traits.

<?php
namespace FrontendBundle\Traits\Entity;

trait GetEntityNameTrait {

    public static function getEntityName()
    {
      return str_replace('\\', '\\\\', get_parent_class());
    }
}

I use this trait in any of this entities, but I'm getting following compile error.

Compile Error: Cannot redeclare class FrontendBundle\Entity\Country

I tried several reflection methods all are the same result is this a bug or something is not logical ?

Others:

get_parent_class()      
get_class()
get_called_class()
__CLASS__





How can I get the value type of an enum member

For example

template EnumValueType(T)
if (is(T == enum))
{
    alias EnumValueType = /* ??? */;
}

enum E: ubyte {e0 = 123}
enum D: float {d0 = 0.5}

void main()
{
    E e;
    D d;
    assert( is(EnumValueType!(typeof(e)) == ubyte));
    assert( is(EnumValueType!(typeof(d)) == float));
}

So far I can only detect if it's a enum. I see a way to do this but it's bad. It would consist in iterating trough an AliasSeq seq made of D basic types and to see if a T is convertible to seq[n].

Any other idea ?





vendredi 25 décembre 2015

Casting an object to a another certain object, then modifying it

So here's what I'm trying to do. At the beginning of the program, the class looks through all the fields in that class. If the field is a specific type of object, then it adds it to the list. The list of certain objects can be called later on, and modified.

SORRY, forgot to post the actual error. When I try to cast the class to the type Value, I get this error:

Cannot cast from Class<capture#8-of ?> to Value<?>

Here's the main part:

private List<Value> values = new ArrayList<Value>();

for (Field f : getClass().getDeclaredFields()) {
        if (f == null)
            continue;
        Class<?> clazz = f.getType();
        if (clazz.isAssignableFrom(Value.class)) {
            Value<?> value = (Value) clazz;
            list.add(value);
        }
    }

Here's the Value class:

public class Value<E> {

private String name;
private E value;

public Value(final String name, final E value) {
    this.name = name;
    this.value = value;
}

public final String getValueName() {
    return name;
}

public final E getValue() {
    return value;
}

public final void setValue(final E newValue) {
    value = newValue;
}

Is there any way to do this?





I am geting NullpointerException when I invoke method using java reflection [duplicate]

This question already has an answer here:

I am geting NullpointerException when I invoke method using java reflection
can somebody please help

JUNIT TEST CASE

I am trying to test method
private boolean isHoliday(DateCalculationParams dateCalculationParams,Date date) in Class DateCalculationService and i want to mock holidayDlService.isHoliday(holiday)

package colruyt.calendarejb.service.bl;

import static org.junit.Assert.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.mockito.Mockito.*;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import colruyt.calendarejb.bo.DateCalculationParams;
import colruyt.calendarejb.bo.Holiday;
import colruyt.calendarejb.bo.LogicalCalendar;
import colruyt.calendarejb.exception.CountryNotSupportedException;
import colruyt.calendarejb.exception.InvalidCombinationException;
import colruyt.calendarejb.exception.InvalidDateCalculationParamsException;
import colruyt.calendarejb.exception.InvalidHolidayException;
import colruyt.calendarejb.exception.InvalidLogicalCalendarException;
import colruyt.calendarejb.service.dl.HolidayDlService;
import colruyt.calendarejb.util.LogicalCalendarStartdayCts;
import colruyt.calendarejb.util.LogicalCalendarTypeCts;

public class DateCalculationServiceTest {

DateCalculationService dcs;

@Before
public void setUp() throws Exception {
dcs = spy(new DateCalculationService());

}


@Test
public final void isHolidayTest() throws InvalidCombinationException,         CountryNotSupportedException,
        InvalidHolidayException, NoSuchMethodException, SecurityException,        IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {

    DateCalculationParams dcp = new DateCalculationParams();
    dcp.setCountry("IN");
    Date d = new Date();
    Holiday holiday = new Holiday();
    holiday.setDate(d);
    Boolean b = true;
    HolidayDlService holidayDlService = mock(HolidayDlService.class);
    when(holidayDlService.isHoliday(holiday)).thenReturn(true);
    // doReturn(true).when(hs).isHoliday(holiday);
    Method privateStringMethod =                                  DateCalculationService.class.getDeclaredMethod("isHoliday",
            DateCalculationParams.class, Date.class);

    privateStringMethod.setAccessible(true);
//I am getting nullpointer exception at this line
    Boolean s = (Boolean) privateStringMethod.invoke(dcs, dcp, d);

    assertTrue(b);

}

}

Following is the class and method I am testing Class Under Test

Class DateCalculationService{

private boolean isHoliday(DateCalculationParams dateCalculationParams,

    Date date) {

    Holiday holiday = new Holiday();
    holiday.setDate(date);
    boolean isHoliday;
    if (dateCalculationParams.getCountry() != null) {
        holiday.setCountryCode(dateCalculationParams.getCountry());
    }
    try {

   isHoliday = holidayDlService.isHoliday(holiday);

    } catch (InvalidHolidayException e) {

    } 
return isHoliday;
}
}





jeudi 24 décembre 2015

Get a field's value

I want to get the value with which the field is being initialized. Example:

class ClassA {
  public String someString = "Merry Christmas";
}

class ClassB {
 String anotherString = ClassA.class.getField("someString");
}

Is there any way to do this?





How to efficiently group all implementations by interface from multiple assemblies?

I want to create a grouping using Linq that gives me back all implementation types keyed by the interface being implemented.

Basically, given a number of types in a number of assemblies, I want to get all interfaces that have at least one implementation that matches a certain criteria, and then for those interfaces I need to then get all implementations.

For example, suppose I have these classes:

interface IDoX {}

interface IDoY {}

interface IDoZ {}

class Impl1 : IDoX, IDoY {}

class Impl2 : IDoY {}

class Impl3 : IDoY, IDoZ {}

class Impl4 : IDoX, IDoY, IDoZ {}

Grouping these classes and interfaces, I should get back a result like this (in dictionary form, for example):

{
    IDoX, {Impl1, Impl4},
    IDoY, {Impl2, Impl3, Impl4},
    IDoZ, {Impl3, Impl4}
}

I need this because I have to analyze all implementations of a given interface to take a decision, and I need to do this across all loaded assemblies.

I'm trying to come up with something but since the reflection classes all give me back the results in the other direction it's kinda weird to do. For example, to get all implementations of a given interface, I need to search all assemblies and then check for each type if they implement the interface or not.

A naive approach to this lookup building would result in an insane amount of iterations. Is there a clean way of achieving this grouping that I need, or will I have to resort to a crazy amount of repeated iteration over all types on all assemblies?





Find all classes that derive from type and activate that type

I have already looked at some similar answers but I cannot get it to work.

I am attempting to make the following more maintainable:

var modules = new INinjectModule[]
{
    new ServiceModule(),
    new ApplicationSettingsModule(),
    new SerializerModule(),
    new LoggerModule(),
    new SqliteModule(),
    new SetupModule(), 
    new CacheModule(), 
    new AuthenticationModule(), 
};

Every time I add a new NinjectModule I need to modify this array to include it.

I want to be able to find all types that derive from NinjectModule and activate them and put them all into a collection.

This is what I have tried but I am not getting any of my classes that derive from NinjectModule

var classes = (from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
                from assemblyType in domainAssembly.GetTypes()
                where typeof(NinjectModule).IsAssignableFrom(assemblyType)
                select assemblyType).ToArray();





Dynamically create executing code in C#

So, I have strange question (maybe so stupid), but... So, my task. I have same class which gives me same functionality. So, in the main program, which I realize (yes, it's client-server app)) , I want to dynamically create ".exe wrapper" for this class - simplest code like this:

class Program
{
    private SameClass mySameClass;

    static void Main(string[] args)
    {
        mySameClass = new mySameClass(args);
        Console.Readline();
    }
}

In general, I want to create main app which creates slaves in the independent proccesses via dynamically code generation. So, how to make it and control it? Thank you.





mercredi 23 décembre 2015

Loading Fragments using reflection causes "java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation"

I am developing android Enterprise application where i want to use some file on run-time.I am able to use simple class using Java Reflection and i also want to use Fragment.

E.g.- I have created TestingDummyJar.jar and placed in SDCard.
Usage - First I am loading this jar using DexClassLoader and then loading class. its working perfectly for Simple class as -

final File tmpDir = this.getDir("dex", 0);
classloader = new DexClassLoader("/SDcard/TestingDummyJar.jar", tmpDir.getAbsolutePath(), null, this.getClassLoader());
mLoadedClass = (Class) classloader.loadClass("com.example.testingdummyjar.ScrollerCustomDuration");

But when i try to load Fragment as-
mLoadedClass = (Class) classloader.loadClass("com.example.testingdummyjar.ScrollerCustomDuration");

throw Exception "java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation"





There is any drawback in using reflection to copy objects?

I'm using reflection to copy data between objects who implement the same interface, everything seems to work fine, but before deploying to production I wanted to ask: is there any reason why I should avoid doing this?

My previous implementation with hard-coded properties was not able to detect additions to the interface nor was able to avoid me or my team to mistakenly copy a property to another of the same type.

Also, I'm caching on a static dictionary the properties by type, does this have any advantage or i'm just doubling the CLR dictionary?





JAVA - Primitive type VS Object type

I have following variables:

Class a = int.class;
Class b = Integer.class;

Is it possible to compare it dynamically? It means that I want to get primitive tye of second variable and compare it with first.





Insert/update database dynamically with Entity Framework

I've to import the values of multiple SharePoint 2013 lists in a SQL Server database using Entity Framework. I thought to use two database tables where store the names of the lists and the related columns with the database tables and columns and with these informations to loop automatically inserting/updating the database.

These are the tables where I store list informations:

SP List to SQL Server mapping tables

For example there is a SharePoint list called Person with column Name, Surname and Age where Age is a Choice field as drop down containing numbers. From T_SPLists and T_SPColumns I know that all the data goes into Person table with this mapping:

  • Name ---> Name
  • Surname ---> Surname
  • Age is a foreign key in Person table and I've to check in the lookup table if the value exists; if not add it in lookup table and insert the correct id into Person table (the final user will ask to insert a new value in the drop down everytime he will need it), if already exists get the id and insert into Person table

How can I do it with Entity Framework? I hope I have been clear.

Thank you





golang reflect for sql scan report error

/**
-- name is character varying(64)
CREATE TABLE users
(
  id bigint NOT NULL,
  no character(24),
  identity name,
  name name,
  head character varying(256),
  email character varying(256),
  site character varying(256),
  create_time timestamp without time zone,
  city_id bigint,
  timezone jsonb,
  update_time timestamp without time zone,
  CONSTRAINT user__pk PRIMARY KEY (id)
)

spottly=# SELECT "id", "no", "identity", "name", "head", "email", "site", "create_time", "city_id", "update_time", "timezone" FROM "users" WHERE "email" = 'fixopen@yeah.net' LIMIT 1 OFFSET 0;
       id       | no | identity |  name   |                  head                  |      email       |            site            | create_time | city_id | update_time | timezone
----------------+----+----------+---------+----------------------------------------+------------------+----------------------------+-------------+---------+-------------+----------
 95083655397376 |    | fixopen  | fixopen | /uploader/52e2762edf4e633666000867.png | fixopen@yeah.net | http://ift.tt/1IqFt14 |             |         |             |
(1 row)
*/

package main

import (
    "database/sql"
    //"errors"
    "fmt"
    _ "github.com/lib/pq"
    "log"
    "net/url"
    "reflect"
    "strings"
    "time"
)

type User struct {
    Id          uint64    `json:"id"`
    No          *string   `json:"no"`
    Identity    string    `json:"identity"`
    Name        string    `json:"name"`
    Head        url.URL   `json:"head"`
    Email       *string   `json:"email"`
    Site        url.URL   `json:"site"`
    Create_time time.Time `json:"create-time"`
    City_id     *uint64   `json:"city-id"`
    Update_time time.Time `json:"update-time"`
    Timezone    *string   `json:"timezone"`
}

func main() {
    connectionString := "host=localhost port=5432 user=postgres dbname=spottly password=123456 sslmode=disable"
    db, err := sql.Open("postgres", connectionString)
    defer db.Close()
    if err != nil {
        log.Fatal(err)
    }

    t := reflect.TypeOf(User{})
    //u := reflect.New(t).Elem().Interface()
    //fmt.Printf("u is %T, %#v\n", u, u)

    resultValuePtr := reflect.New(t)
    resultValue := resultValuePtr.Elem()
    fieldCount := t.NumField()
    fields := make([]reflect.StructField, fieldCount)
    for i := 0; i < fieldCount; i++ {
        fields[i] = t.Field(i)
    }
    columns := make([]string, fieldCount)
    fieldAddrs := make([]interface{}, fieldCount)
    for i := 0; i < fieldCount; i++ {
        columns[i] = strings.ToLower(fields[i].Name)
        fieldAddrs[i] = resultValue.Field(i).Addr().Interface()
    }
    columnNames := strings.Join(columns, "\", \"")
    command := "SELECT \"" + columnNames + "\" FROM \"users\" WHERE \"email\" = 'fixopen@yeah.net' LIMIT 1 OFFSET 0"
    fmt.Printf("query command is %v\n", command)
    // fmt.Printf("meta field is %v\n", fields)
    // fmt.Printf("field addr is %#v\n", fieldAddrs)
    err = db.QueryRow(command).Scan(fieldAddrs...)
    if err == nil {
        result := resultValuePtr.Interface()
        fmt.Printf("result is %#v\n", result)
    } else {
        fmt.Printf("Select one error is %v\n", err)
        //panic(errors.New("halt"))
    }
}

database schema and data show in comment.

the query command is:

SELECT "id", "no", "identity", "name", "head", "email", "site", "create_time", "city_id", "update_time", "timezone" FROM "users" WHERE "email" = 'fixopen@yeah.net' LIMIT 1 OFFSET 0

same as comment, this command execute with psql return one row data.

sql Scan method execute error, output:

Select one error is sql: Scan error on column index 4: unsupported driver -> Scan pair: []uint8 -> *url.URL

My golang version is go version go1.5.2 darwin/amd64

PostgreSQL version is 9.4.2

use github.com/lib/pq access DB.

It's the db driver not support scan string column to url.URL?

what do I can?





golang reflect create object is error

less main.go output:

```

package main

import (
    "reflect"
    "net/url"
    "fmt"
)

type User struct {
    Id uint64 `json:"id"`
    No *string `json:"no"`
    Identity string `json:"identity"`
    Head url.URL `json:"head"`
}

func main() {
    t := reflect.TypeOf(User{})
    u := reflect.New(t).Elem().Interface()
    fmt.Printf("u is %T, %v\n", u, u)
}

```

go version output:

go version go1.5.2 darwin/amd64

go build main.go correct

./main output:

u is main.User, {0 <nil> { <nil> }}

what the matter?? why u object only third field? the User struct include four field!

In my really project, I find the created object's field's type is incorrect





Swift: NSClassFromString and NSStringFromClass behave different for NSManagedObjects

NSStringFromClass delivers fully qualified class names for class references like <ClassName>".self"

NSStringClassFromString delivers a class reference of kind AnyClass for fully qualified class names like <AppId>"."<ClassName">.

But it behaves different for subclasses of NSManagedObject.

Let's say the AppId is "MyApp".

class Foo: NSObject {}

@objc(Bar)
class Bar: NSManagedObject {}

print(NSStringFromClass(Foo.self))        // MyApp.Foo
print(NSStringFromClass(Bar.self))        // Bar

print(NSClassFromString("Foo"))           // nil
print(NSClassFromString("Bar"))           // MyApp.Bar
print(NSClassFromString("MyApp.Foo"))     // MyApp.Foo
print(NSClassFromString("MyApp.Bar"))     // nil

That can lead to problems, when creating the input for NSClassFromString dynamically, e.g. by concatenating the 'AppId' with the class name determined by MyClass.self. It seems that subclasses of NSManagedObject don't belong to the Apps namespace.

It's interesting. The functions are reversive.

let fco = NSClassFromString(NSStringFromClass(Foo.self))
let fct = NSClassFromString(NSStringFromClass(fco!))
// fco == fct    

let bco = NSClassFromString(NSStringFromClass(Bar.self))
let bct = NSClassFromString(NSStringFromClass(bco!))
// bco == bct

But the intermediate results differ, as you can see in the upper listing.

Serious question: Is this a bug or a feature? If it's a feature, what are the reasons and advantages.





Check whether PropertyInfo.SetValue will throw an ArgumentException

I have inherited some code that tries to set a property:

try
{
    propertyInfo.SetValue(object, value, null);
}
catch (ArgumentException)
{
    // look for a TypeConverter to use instead
}

In current usage the exception is caught and thrown a lot, so I would like to make a check first:

if (propertyInfo.PropertyType.IsAssignableFrom(value.GetType())
{
    // Try/catch as above
}
else
{
    // look for a TypeConverter to use instead, as above
}

This runs much faster. However, my one concern is that IsAssignableFrom returns false in some cases where SetValue would in fact succeed. The spec for SetValue says

value cannot be converted to the type of PropertyType

which is not exactly the same as assignability.

(If IsAssignableFrom returns true in cases where SetValue fails, that's fine - the throw/catch will still do the job.)

Can someone confirm for me whether this is possible or not?





mardi 22 décembre 2015

Java - Got Exception when Proxy method return type is Future

I'm trying Proxy, implemented InvocationHandler:

public interface IDataInterface {
    public Future<String> getFuture();
}

public class MyData implements IDataInterface {
    private String data = "abc";

    @Override
    public Future<String> getFuture() {
        Callable<String> callMe = () -> {
            TimeUnit.SECONDS.sleep(5);
            return data;
        };
        FutureTask<String> task = new FutureTask<String>(callMe);
        task.run(); // must call run(), or it will block forever!
        return task;
    }
}

public class MyInvocationHandler implements InvocationHandler {
    private final Object delegate;
    private final ExecutorService scheduler;

    public MyInvocationHandler(Object obj) {
        this.delegate = obj;
        scheduler = Executors.newCachedThreadPool();
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.printf("[Proxy] Will call method: %s\n", method.getName());

        Object result = null;
        if(Future.class.isAssignableFrom(method.getReturnType())) {
            Callable<Object> methodRequest = () -> {
                Object res = method.invoke(delegate, args);
                return res;
            };
            Future<Object> future = scheduler.submit(methodRequest);
            scheduler.shutdown();
            result = future;
        } else {
            result = method.invoke(delegate, args);
        }
        // this will cause definite loop!
        // Object result = method.invoke(proxy, args);
        System.out.println("[Proxy] After method call.");
        return result;
    }
}

In main method, I run:

IDataInterface myData = (IDataInterface)Proxy.newProxyInstance(
                                                        IDataInterface.class.getClassLoader(),
                                                        new Class<?>[] { IDataInterface.class },
                                                        new MyInvocationHandler(new MyData()));
        Future<String> future = myData.getFuture();
        try {
            System.out.println(future.get().toString());
        } catch(InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

Got following Exception saying java.util.concurrent.FutureTask cannot be cast to java.lang.String:

[Proxy] Will call method: getFuture
[Proxy] Method return type is Future.
[Proxy] After method call.
Get data.Exception in thread "main" java.lang.ClassCastException: java.util.concurrent.FutureTask cannot be cast to java.lang.String
     at others.proxy.Main.main(Main.java:19)

What's the root cause?





Reflection to Get `Parent` Object

I'm pretty sure this isn't possible, but thought I'd ask anyways.

Say I have:

public class A
{
    public B BInstance { get; set; }
}

public class B
{
    public Type GetParentType()
    {
        //...
    }
}

Is there any possible way, via reflection, for B's GetParentType to return typeof(A) at runtime?

I know I could simply pass typeof(this) into B when I initialize it on A, I'm just curious.





Using index with Array reflection [duplicate]

This question already has an answer here:

I created an array using reflection

var obj = Array.CreateInstance(propertyInfo.FieldType,len);

I want to set obj[0] to some value, how should I do it?





How to list all classes conforming to protocol in Swift?

How to list all classes implementing a given protocol in Swift?

Say we have an example:

protocol Animal {
    func speak()
}

class Cat:Animal {
    func speak() {
        print("meow")
    }
}

class Dog: Animal {
    func speak() {
        print("Av Av!")
    }
}

class Horse: Animal {
    func speak() {
        print("Hurrrr")
    }
}

Here is my current (not compilable) approach:

func getClassesImplementingProtocol(p: Protocol) -> [AnyClass] {
    let classes = objc_getClassList()
    var ret = [AnyClass]()

    for cls in classes {
        if class_conformsToProtocol(cls, p) {
            ret.append(cls)
        }
    }
    return ret
}

func objc_getClassList() -> [AnyClass] {
    let expectedClassCount = objc_getClassList(nil, 0)
    let allClasses = UnsafeMutablePointer<AnyClass?>.alloc(Int(expectedClassCount))
    let autoreleasingAllClasses = AutoreleasingUnsafeMutablePointer<AnyClass?>(allClasses)
    let actualClassCount:Int32 = objc_getClassList(autoreleasingAllClasses, expectedClassCount)

    var classes = [AnyClass]()
    for i in 0 ..< actualClassCount {
        if let currentClass: AnyClass = allClasses[Int(i)] {
            classes.append(currentClass)
        }
    }

    allClasses.dealloc(Int(expectedClassCount))

    return classes
}

But when calling either

getClassesImplementingProtocol(Animal.Protocol) or

getClassesImplementingProtocol(Animal) or

getClassesImplementingProtocol(Animal.self)

results in Xcode error: cannot convert value of type (Animal.Protocol).Type to expected argument type 'Protocol'.

Did anyone manage get this working?





Alternative to switch(name_of_type) and maps when printing data?

Suppose I have a function with the following signature:

void print_elements(void* b, const std::string element_type_name, size_t len, std::ostream& os);

Which is supposed to print/stream the len elements of b to output stream os. Obviously I can't do

const size_t element_size = size_by_type_name(element_type_name);
for(it = b; it < (b + len * element_size); it++) {
    auto& stream_op_wrapper = get_stream_op_wrapper_for(os, element_type_name);
    stream_op(os, it);
}

in C++. What do I do instead? I know C++ doesn't have reflection, but can I do better than looking up each time in a table of types? Or using static maps of string-to-typpe_info's ?





getting fields of a class with reflection

good day. I'm trying to get 2 static fields of a class, but I can't make it work. I'm trying to get the fields [event] and [adduserlocation]. this is code-behind page of asp.net webform. any help greatly appreciated

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
public partial class test2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var type = typeof(FormBLL).GetType();
        var fieldInfos = type.GetFields(BindingFlags.Instance |
                   BindingFlags.Static |
                   BindingFlags.NonPublic |
                   BindingFlags.Public);

        var q = fieldInfos.ToList();
        foreach(var f in q)
        {
            Response.Write(f.Name + "<br/>");
        }

    }

    public static class FormBLL
    {
        public static string @event = "abc";

        public static string adduserlocation = "123";


    }

}





Swift: Reflecting properties of subclass of NSManagedObject

When accessing the inner structure of a subclass of NSManagedObject using a Mirror, all managed variables are ignored.

public class Foo: NSManagedObject {
   @NSManaged var bar: String?
}

var f: Foo = ...
// ... creating a Foo in a valid context ...

let mirror = Mirror(reflecting: f)
for c in mirror.children {        // children count == 0
  print("\(c.label!):\(c.value)") // never executed
}

How can reflection mechanisms used on NSManagedObjects.





lundi 21 décembre 2015

Avoiding reflection - How best can I refactor this code?

I started experimenting with Go, and so far it's been a blast. I decided to make a small app which will help a friend organize information business-related information in his (small) company, and I thought I would use Go to implement it.

I haven't (exactly) run into a problem, it's more of a question, when should I consider using reflection? For example, I have 3 related types: Company, Project and Staff. They all have several fields in common (such as id,name) so as you can imagine, the functions that load them from the database (I'm using MySQL) are all very similar.

Look at LoadCompany(), LoadStaff(), and LoadProject() :

// Loads the company from the database with the given id.
func LoadCompany(id int) (Company, error) {
    db := tools.OpenDB()
    defer db.Close()
    stmt, err := db.Prepare(`SELECT full_name AS fullName, short_name AS name, history, overview, est, phone, website, email
                                FROM companies WHERE id = ?`)
    if err != nil {
        log.Panic(err)
    }   
    c := Company{id: id} 
    err = stmt.QueryRow(c.id).Scan(&c.FullName, &c.Name, &c.History, &c.Overview, &c.Est, &c.Phone, &c.Website, &c.Email)
    if err != nil {
        return Company{}, err 
    }   
    return c, nil 
}

// Loads the staff from the database with the given id.
func LoadStaff(id int) (Staff, error) {
    db := tools.OpenDB()
    defer db.Close()
    stmt, err := db.Prepare(`SELECT full_name AS fullName, short_name AS name, email, joined, ` + "`left`" + `, history, phone, position
                                FROM staff WHERE id = ?`)
    if err != nil {
        log.Panic(err)
    }
    s := Staff{id: id}
    err = stmt.QueryRow(s.id).Scan(&s.FullName, &s.Name, &s.Email, &s.Joined, &s.Left, &s.History, &s.Phone, &s.Position)
    if err != nil {
        return Staff{}, err
    }
    return s, nil
}

// Loads the project from the database with the given id.
func LoadProject(id int) (Project, error) {
    db := tools.OpenDB()
    defer db.Close()
    stmt, err := db.Prepare("SELECT * FROM projects WHERE id = ?")
    if err != nil {
        log.Panic(err)
    }
    p := Project{}
    err = stmt.QueryRow(id).Scan(&p.id, &p.Title, &p.Overview, &p.Value, &p.Started, &p.Finished, &p.Client, &p.Architect, &p.Status)
    if err != nil {
        return Project{}, err
    }
    return p, nil
}

When I wrote LoadCompany(), I was feeling pretty good about myself (ahem as a beginner/intermediate programmer) because it seemed minimal and clean. But as I wrote LoadStaff() and LoadProject(), all I was doing is copying and tweaking. I'm certain there's a better way to do this, but I'm weary of jumping into reflection, after reading Pike's post on it:

[Reflection is] a powerful tool that should be used with care and avoided unless strictly necessary.

So my question is, should I use reflection, and if so, can you give me some pointers on the best technique for something like this? This is only the tip of the iceberg, because I feel as though the rest of the functions and methods relating to these types are all similarly repetitive (and don't get me started on the tests!).

Thanks!





How could std::experimental::source_location be implemented?

C++ Extensions for Library Fundamentals, Version 2 (N4564) introduces the type std::experimental::source_location.

§ 14.1.2 [reflection.src_loc.creation] says:

static constexpr source_location current() noexcept;

Returns: When invoked by a function call (C++14 § 5.2.2) whose postfix-expression is a (possibly parenthesized) id-expression naming current, returns a source_location with an implementation-defined value. The value should be affected by #line (C++14 § 16.4) in the same manner as for __LINE__ and __FILE__. If invoked in some other way, the value returned is unspecified.

Remarks: When a brace-or-equal-initializer is used to initialize a non-static data member, any calls to current should correspond to the location of the constructor or aggregate initialization that initializes the member.

[ Note: When used as a default argument (C++14 § 8.3.6), the value of the source_location will be the location of the call to current at the call site. — end note ]

If I understand correctly, then the feature is intended to be used like this.

#include <experimental/source_location>  // I don't actually have this header
#include <iostream>
#include <string>
#include <utility>

struct my_exception
{

  std::string message {};
  std::experimental::source_location location {};

  my_exception(std::string msg,
               std::experimental::source_location loc = std::experimental::source_location::current()) :
    message {std::move(msg)},
    location {std::move(loc)}
  {
  }

};

int
do_stuff(const int a, const int b)
{
  if (a > b)
    throw my_exception {"a > b"};  // line 25 of file main.cxx
  return b - a;
}

int
main()
{
  try
    {
      std::cout << do_stuff(2, 1) << "\n";
    }
  catch (const my_exception& e)
    {
      std::cerr << e.location.file_name() << ":" << e.location.line() << ": "
                << "error: " << e.message << "\n";
    }
}

Expected output:

main.cxx:25: error: a > b

Without std::experimental::source_location, we might have used a helper macro THROW_WITH_SOURCE_LOCATION that internally makes use of the __FILE__ and __LINE__ macros to initialize the exception object properly.

I was wondering how a library could implement std::experimental::source_location. Unless I'm completely missing the point, doing so is not possible without special compiler support. But what kind of magic compiler features would be needed to make this work? Would it be comparable to the trick deployed for std::initializer_list? Is there any experimental implementation of this feature available to look at? I have checked the SVN sources for GCC but didn't find anything yet.





Best way to initialize unknown types with parameters?

I'm trying to genericize some of our code by being able to instantiate objects that inherit from a base class without knowing the types of those objects. So I want to just be able to drop a dll in a directory and be able to instantiate those objects.

I was looking into MEF, but I can't export the parameters because they're not defined in code (loaded from a database). So it doesn't look like MEF is the way to go.

Reflection works great, but that seems too fragile to rely on.

Is there something I'm missing that would allow me to do this with MEF, is there another framework that would allow me to do this better, or is reflection simply the answer here?





Get private field types of current class,composed class,super class using reflection api [duplicate]

This question already has an answer here:

Here is my scenario:

Class A{
private Long aId;
}

Class C{
private BigDecimal decValue;
}

Class B extends A{
private Integer intValue;
private C c;
}

I have an instance of Class B(B b = new B()). with this instance of b i am trying to retrieve type of field aId in classA and type of field decValue in Class C.

I tried: Based on this java doc

  b.getDeclaredField("intValue").getType();//this works
    b.getDeclaredField("aId").getType();//Doesnt work, private field in super class
    b.getDeclaredField("decValue").getType();//Doesnt work, private field in composed

class I also tried getField, this doesnt give access to private fields.

what i am expecting:

 b.getDeclaredField("aId").getType();//should return Long.Class.
  b.getDeclaredField("decValue").getType();//Should return BigDecimal.class

Any help is appreciated.





C# expression, VS converts enum to int but not LinqPad

Suppose this fairly simple expression:

Expression<Func<DayOfWeek, bool>> filter = d => d == DayOfWeek.Friday;

In LinqPad I get an UnaryExpression for the right part, which is what I want, so I can work with the enum value and type:

Expected result in LinqPad

However, in a VS, I get a totally different ConstantExpression which converts the value to an integer:

Result in VS

I really have no clue why this is happening. Is there a global setting I'm missing in VS or something?

It happens in VS 2015 AND 2010 as well.





Getting property implementing interface property for non virtual property with reflection

So, I thaught I have a solution for getting a PropertyInfo when having a concrete class, and a PropertyInfo for an interface implemented by the concrete class. Here is the code:

public static PropertyInfo GetImplementingProperty(Type concreteType, PropertyInfo interfaceProperty)
        {

            // do some region parameter check, skipped
            var interfaceType = interfaceProperty.DeclaringType;
            //use the set method if we have a write only property
            var getCorrectMethod = interfaceProperty.GetGetMethod() == null
                ? (Func<PropertyInfo, MethodInfo>) (p => p.GetSetMethod(true))
                : p => p.GetGetMethod(true);
            var propertyMethod = getCorrectMethod(interfaceProperty);
            var mapping = concreteType.GetInterfaceMap(interfaceType);

            MethodInfo targetMethod = null;
            for (var i = 0; i < mapping.InterfaceMethods.Length; i++)
            {
                if (mapping.InterfaceMethods[i] == propertyMethod)
                {
                    targetMethod = mapping.TargetMethods[i];
                    break;
                }
            }

            foreach (var property in concreteType.GetProperties(
                BindingFlags.Instance | BindingFlags.GetProperty |
                BindingFlags.Public | BindingFlags.NonPublic)) // include non-public!
            {
                if (targetMethod == getCorrectMethod(property)) // include non-public!
                {
                    return property;
                }
            }

            throw new InvalidOperationException("The property {0} defined on the interface {1} has not been found on the class {2}. That should never happen."
                .FormatText(interfaceProperty.Name, interfaceProperty.DeclaringType.FullName, concreteType.FullName));
        }

Unfortunately I found a case where it fails, and I am unsure how to fix this. So I have in a dll a class:

public abstract class BaseClass
{
    public Guid ConfigId { get; set; }
    public virtual Guid ConfigId2 { get; set; }
}

Then in another dll I do:

    interface INamed
    {
        Guid ConfigId { get; }
        Guid ConfigId2 { get; }
    }

    private class SuperClass : BaseClass, INamed
    {
    }

Now

        ReflectionHelper.GetImplementingProperty(typeof(SuperClass), typeof(INamed).GetProperty("ConfigId2")); // this works
        ReflectionHelper.GetImplementingProperty(typeof(SuperClass), typeof(INamed).GetProperty("ConfigId")); // this fails

Any idea how do I match up the ConfigId property to the Base class proprety definition?

PS. I have attributes on the concrete class properties, thats why i need to get those.

Any help appreciated!





getParameters() should return an array and this code should succeed in the jdk 7 maven project

                private void setPropertiesToBasePojoMarkerImpl(Object obj, Method[] methods) {
                for (Method method : methods) {
                    if (method.getName().contains("get") && !method.isAnnotationPresent(Worker.class)
                            && !method.getName().contains("getClass") && isPojoMarkerMethod(method)
                            && method.getParameters().length == 0) {
// in the above condition it says the method getParameters() is undefined for type Method
                        try {
                            Serializable result = (Serializable) method.invoke(obj, new Object[0]);
                            if (result != null) {
                                if (staticRegistry.isReferencePresent(result) != null)
                                    result = staticRegistry.isReferencePresent(result);
                            }
                            String propname = method.getName().toString().substring(3).toLowerCase();
                            beanEnhancer.getServerBasePojoMarkerImpl().setProperty(propname, result);
                        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                            logger.log(Level.WARNING, "unable to invoke method with name" + method.getName() + " "
                                    + e);
                        }
                    }
                }

So the issue here is that its a maven project with JDK 7 source configuration. It builds flawlessly on linux and windows machines. On my mac book pro it consistently says the said method is unavailable for type Method.

I am certain this method should be available on all builds of JDK 7.

Any clues ?





Reflect scala type of object, trait or class

In Scala-Play app, I want to use play.api.Logger.info(s"Message | $sessionID | ${this.getClass}"), where $sessionID is already defined and added to identify the user. $this.getClass - is not yet implemented and is my question - being in different places of code (objects, traits, classes), when logging something, I want to add information about the place in code where the log message occurred - that is I want to reflect on type of object, trait or class that called the logger. What would be the easiest way to do so in Scala?





C# search child java-window elements

I want to search window's controls by handle in C# code, whenever the other window is a java window.

The following link works on windows application: C# get child handles using FindWindowEx by name and ordinal number

When the searched window is java application window, I don't know how to search it, because "TextBox" in java is not "TextBox" in C#.

How can I search the controls of the other window, whenever the other window is java application window? (By some reflection or any other attitude).





dimanche 20 décembre 2015

Should the usage of reflection be avoided in Go?

I'm new to Go and also new to the concept of reflection, but should or can the usage of reflect package be avoided in Go? Is there a scenario where reflect is unavoidable?





Or switch cases with reflection discretization

In class DataTuple.java. I have this attributes

//Ints position
public int pacmanPosition;
public int blinkyDist = -1;
public int inkyDist = -1;
public int pinkyDist = -1;
public int sueDist = -1;

//Enum Move {UP, DOWN, LEFT, RIGHT, NEUTRAL}
public MOVE blinkyDir;
public MOVE inkyDir;
public MOVE pinkyDir;
public MOVE sueDir;

//booleans
public boolean isBlinkyEdible = false;
public boolean isInkyEdible = false;
public boolean isPinkyEdible = false;
public boolean isSueEdible = false;

Here is the function discretize. it's like or cases. 4 cases. 1 for MOVE's, 2 and 3 for ints, 4 for booleans.

public String discretize(String string) {
    // TODO Auto-generated method stub
    Field field = this.getClass().getDeclaredField(string);
    field.setAccessible(true);

    switch (string) {
        case "DirectionChosen":
        case "blinkyDir":
        case "inkyDir":
        case "pinkyDir":
        case "sueDir":
            MOVE direction = (MOVE) field.get(this);
            return direction.toString();
            break;
        case "pacmanPosition":
            //Here i don't need use the reflection
            return discretizePosition(this.pacmanPosition).toString();
        case "blinkyDist":
        case "inkyDist":
        case "pinkyDist":
        case "sueDist":
            int distance =  (int) field.get(this);
            return discretizeDistance(distance).toString();
            break;
        case "isBlinkyEdible":
        case "isInkyEdible":
        case "isPinkyEdible":
        case "isSueEdible":
            String bool = (String) field.get(this);
            return bool;    
            break;

        default:
        break;
    }
}

discretizePosition and discretizeDistance return a DiscreteTag. Param: double

public enum DiscreteTag {
    VERY_LOW, LOW, MEDIUM, HIGH, VERY_HIGH, NONE;

    public static DiscreteTag DiscretizeDouble(double aux) {
        if (aux < 0.1)
            return DiscreteTag.VERY_LOW;
        else if (aux <= 0.3)
            return DiscreteTag.LOW;
        else if (aux <= 0.5)
            return DiscreteTag.MEDIUM;
        else if (aux <= 0.7)
            return DiscreteTag.HIGH;
        else
            return DiscreteTag.VERY_HIGH;
    }
}

in class decTree.java. Here I want to put the string attribute with the string name of the attribute i want. Example:

String attribute = "DirectionChosen" 
DataTuple tuple = ...; //value of tuple.DirectionChosen = MOVE.UP 

Here i want to return a string. In this case is "UP" it's equal to another string like "UP" or other string i want to pass

if(tuple.discretize(attribute)=="UP") {
  //...
}

The poblem is the reflection. It doesn't work

Field field = this.getClass().getDeclaredField(string);
field.setAccessible(true);

case "sueDist":
        int distance =  (int) field.get(this);
        return discretizeDistance(distance).toString();
        break;





How can I convert the following code to a Compiled Expression in C#?

I have a piece of code which is responsible for creating a generic list using reflection.

public static IList MakeList(Type listType)
{
    // checks to ensure listType is a generic list omitted...

    // gets the generic argument e.g. string for a List<string>
    var genericType = listType.GetGenericArguments()[0];

    return (IList)typeof(List<>)
        .MakeGenericType(genericType)
        .GetConstructor(Type.EmptyTypes)
        .Invoke(null);
}

How can I convert this to a compiled expression to benefit from the performance benefits?





Initialize all channels in a struct using reflect

I have some structs that contain some fields and some channels. I managed to dynamically fill the fields from a map, but how do I initialize the channels? I need to set the size of them as well.

type MyStruct struct {
    ...
    Out           chan *mypackage.OtherStruct `json:"-"`
    Quit          chan struct{}               `json:"-"`
}