mercredi 28 février 2018

Delphi SysUtils.Supports unexpectedly returns true

I am making a eventPublisher based on Spring4d's documentation example

The difference is that subscribers have to explicitly subscribe to events.

I want to trigger their Handle procedure based on wether or not they implement the IEventHandler<TEventType> interface.

When an incoming event is published, I find the IEventHandler<TEventType> type reference using the class name of the event and Spring4d's TType.FindType('IEventHandler<TEvent1>')

Then I loop through my subscribers (objects implementing a IEventHandler interface) and check if it supports the IEventHandler type for example.

The problem is that the Supports method returns true even if the subscriber does not implement the interface.

Also, I tried listing the interfaces of say TMyEventHandler2 type. It contains IEventHandler<TEvent2> ??

I beleive this is due to a limitation with the IEventHandler<TEvent2> and IEventHandler<TEvent1> sharing the same GUID

Is there a workaround for this ?

Using these classes & interfaces :

TEvent1 = class(TObject)
end;

TEvent2 = class(TObject)
end;

IEventHandler = interface(IInvokable)
[guid]
procedure Handle(aEvent : TObject);
end;

IEventHandler<T : class> = interface(IEventHandler)
[guid]
procedure Handle(aEvent : T);
end;

TMyEventHandler1 = class(TObject, IEventHandler, IEventHandler<TEvent1>)
public 
procedure Handle(AEvent : TObject); overload;
procedure Handle(AEvent : TEvent1); overload;
end;

TMyEventHandler2 = class(TObject, IEventHandler, IEventHandler<TEvent2>)
public 
procedure Handle(AEvent : TObject); overload;
procedure Handle(AEvent : TEvent2); overload;
end;

TEventPublisher = class(TObject)
public
  fSubscribers : IList<TValue>;
  procedure Subscribe(aSubscriber : TValue);  // Simply adds the subscriber to the list of subscribers
  procedure Publish(aEvent : TObject); // Publishes an event to the subscribers
end;

procedure TEventPublisher.Publish(const event: TObject; ownsObject: Boolean = True);
const
  IEventSubscriberName = 'IEventSubscriber<*>';
var
  consumerTypeName: string;
  consumerType    : TRttiType;
  intfType        : TRttiInterfaceType;
  subscriber      : TValue;
  subscribed      : IInterface;
  lEventSubscriber: IEventSubscriber;
  lIntfs          : IReadOnlyList<TRttiInterfaceType>;
begin

  consumerTypeName := StringReplace(IEventSubscriberName, '*', GetQualifiedClassName(event), []);
  consumerType     := TType.FindType(consumerTypeName);
  intfType         := consumerType as TRttiInterfaceType;

  for subscriber in fSubscribers do
  begin

    lIntfs := TType.GetType(subscriber.AsObject.ClassInfo).GetInterfaces();

    // lIntfs for TMyEventHandler2 containts IEventHandler<TEvent1> ???

    if Supports(subscriber.AsObject, intfType.GUID, subscribed) then
      if Supports(subscriber.AsObject, IEventSubscriber, lEventSubscriber) then
      begin
        intfType.GetMethod('Handle').Invoke(TValue.From(@subscribed, intfType.Handle), [event])
      end;
  end;

  if ownsObject then
    event.Free;
end;


lEventPublisher := TEventPublisher.Create;
lEventPublisher.Subscribe(TMyEventHandler1.Create);
lEventPublisher.Subscribe(TMyEventHandler2.Create);
lEventPublisher.Publish(TEvent1.Create); // Will both trigger TMyEventHandler1.Handle and TMyEventHandler2.Handle. Why ??





java.lang.NoSuchMethodError Exception with Java reflection in a flink process

I'm trying to extend business logic of a flink process using google Reflection Library. I'm stuck with this exception at runtime. does somebody experimented the same issue. I suspect maven confict but I have no idea. I pasted the exception and the pom file. Anybody could help me?

    22:24:56.552 [main] INFO  org.reflections.Reflections - Reflections took 370 ms to scan 1 urls, producing 16 keys and 52 values 
Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.collect.Sets$SetView.iterator()Lcom/google/common/collect/UnmodifiableIterator;
    at org.reflections.Reflections.expandSuperTypes(Reflections.java:380)
    at org.reflections.Reflections.<init>(Reflections.java:126)
    at org.reflections.Reflections.<init>(Reflections.java:168)
    at org.reflections.Reflections.<init>(Reflections.java:141)
    at it.almaviva.wtf.mms.integratemobilitystatusevent.PassingEventProcess.preferredCustomLogicMethod(PassingEventProcess.java:213)
    at it.almaviva.wtf.mms.integratemobilitystatusevent.PassingEventProcess.main(PassingEventProcess.java:81)

and here the pom file

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>it.almaviva.wtf.mms</groupId>
    <artifactId>mms-integretedmobilitystatusevent-flink-process</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <name>Passing Event Process</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <flink.version>1.4.0</flink.version>
        <!--<slf4j.version>1.7.7</slf4j.version>-->
        <log4j.version>1.2.17</log4j.version>
        <scala.binary.version>2.11</scala.binary.version>
        <junit.version>4.12</junit.version>
        <cassandra.version>3.2.0</cassandra.version>
        <flink.connector.elastic.version>1.4.0</flink.connector.elastic.version>
        <thyco.compiler.version>0.21.0</thyco.compiler.version>
        <jackson.version>2.9.4</jackson.version>
        <cassandra.unit.version>3.3.0.2</cassandra.unit.version>
    </properties>

    <repositories>
        <repository>
            <id>apache.snapshots</id>
            <name>Apache Development Snapshot Repository</name>
            <url>https://repository.apache.org/content/repositories/snapshots/</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
            </snapshots>
        </repository>
    </repositories>

    <!-- Execute "mvn clean package -Pbuild-jar" to build a jar file out of
              this project! How to use the Flink Quickstart pom: a) Adding new dependencies:
              You can add dependencies to the list below. Please check if the maven-shade-plugin
              below is filtering out your dependency and remove the exclude from there.
              b) Build a jar for running on the cluster: There are two options for creating
              a jar from this project b.1) "mvn clean package" -> this will create a fat
              jar which contains all dependencies necessary for running the jar created
              by this pom in a cluster. The "maven-shade-plugin" excludes everything that
              is provided on a running Flink cluster. b.2) "mvn clean package -Pbuild-jar"
              -> This will also create a fat-jar, but with much nicer dependency exclusion
              handling. This approach is preferred and leads to much cleaner jar files. -->

    <dependencies>
        <!-- Apache Flink dependencies -->
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-core</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-java</artifactId>
            <version>${flink.version}</version>
        </dependency>

        <!-- This dependency is required to actually execute jobs. It is currently pulled in by
flink-streaming-java, but we explicitly depend on it to safeguard against future changes. -->
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-clients_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-streaming-java_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-kafka-0.10_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>

        <!-- explicitly add a standard loggin framework, as Flink does not have
                      a hard dependency on one specific framework by default -->

        <!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <!-- TEST PURPOSE -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>
        <dependency>
            <groupId>org.cassandraunit</groupId>
            <artifactId>cassandra-unit-shaded</artifactId>
            <version>3.3.0.2</version>
        </dependency>

        <!-- DATASTAX -->

        <dependency>
            <groupId>com.datastax.cassandra</groupId>
            <artifactId>cassandra-driver-extras</artifactId>
            <version>${cassandra.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.netty</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
                <exclusion>
                    <artifactId>netty-handler</artifactId>
                    <groupId>io.netty</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.datastax.cassandra</groupId>
            <artifactId>cassandra-driver-mapping</artifactId>
            <version>${cassandra.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.netty</groupId>
                    <artifactId>*</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-elasticsearch5_2.11</artifactId>
            <version>${flink.connector.elastic.version}</version>
            <scope>compile</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch-core -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.1.2</version>
        </dependency>

        <dependency>
            <groupId>com.carrotsearch</groupId>
            <artifactId>hppc</artifactId>
            <version>0.7.0</version>
        </dependency>


        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-scala_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-streaming-scala_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-cep_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-statebackend-rocksdb_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-cassandra_${scala.binary.version}</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.flinkspector</groupId>
            <artifactId>flinkspector-datastream_2.11</artifactId>
            <version>0.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.11</version>
            <exclusions>
                <exclusion>
                    <artifactId>guava</artifactId>
                    <groupId>com.google.guava</groupId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <profiles>
        <profile>
            <!-- Profile for packaging correct JAR files -->
            <id>build-jar</id>

            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>

            <dependencies>
                <dependency>
                    <groupId>org.apache.flink</groupId>
                    <artifactId>flink-core</artifactId>
                    <version>${flink.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>org.apache.flink</groupId>
                    <artifactId>flink-java</artifactId>
                    <version>${flink.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>org.apache.flink</groupId>
                    <artifactId>flink-clients_${scala.binary.version}</artifactId>
                    <version>${flink.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>org.apache.flink</groupId>
                    <artifactId>flink-streaming-java_${scala.binary.version}</artifactId>
                    <version>${flink.version}</version>
                    <scope>provided</scope>
                </dependency>
                <dependency>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                    <version>${log4j.version}</version>
                    <scope>provided</scope>
                </dependency>
                <!-- DTO -->
                <dependency>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-databind</artifactId>
                    <version>${jackson.version}</version>
                </dependency>
                <!-- APACHE CASSANDRA -->
                <dependency>
                    <groupId>com.datastax.cassandra</groupId>
                    <artifactId>cassandra-driver-extras</artifactId>
                    <version>${cassandra.version}</version>
                    <exclusions>
                        <exclusion>
                            <groupId>io.netty</groupId>
                            <artifactId>*</artifactId>
                        </exclusion>
                    </exclusions>
                </dependency>
                <dependency>
                    <groupId>com.datastax.cassandra</groupId>
                    <artifactId>cassandra-driver-mapping</artifactId>
                    <version>${cassandra.version}</version>
                    <exclusions>
                        <exclusion>
                            <groupId>io.netty</groupId>
                            <artifactId>*</artifactId>
                        </exclusion>
                    </exclusions>
                </dependency>
                <dependency>
                    <groupId>org.reflections</groupId>
                    <artifactId>reflections</artifactId>
                    <version>0.9.11</version>
                </dependency>

            </dependencies>

            <build>
                <plugins>
                    <!-- disable the exclusion rules -->
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-shade-plugin</artifactId>
                        <version>2.4.1</version>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>shade</goal>
                                </goals>
                                <configuration>
                                    <artifactSet>
                                        <excludes combine.self="override"/>
                                    </artifactSet>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

    <build>
        <plugins>
            <!-- We use the maven-shade plugin to create a fat jar that contains all
          dependencies except flink and it's transitive dependencies. The resulting
          fat-jar can be executed on a cluster. Change the value of Program-Class if
          your program entry point changes. -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <!-- Run shade goal on package phase -->
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <artifactSet>
                                <excludes>
                                    <!-- This list contains all dependencies of flink-dist Everything
                      else will be packaged into the fat-jar -->
                                    <exclude>org.apache.flink:flink-annotations</exclude>
                                    <exclude>org.apache.flink:flink-shaded-hadoop1_2.10</exclude>
                                    <exclude>org.apache.flink:flink-shaded-hadoop2</exclude>
                                    <exclude>org.apache.flink:flink-shaded-curator-recipes</exclude>
                                    <exclude>org.apache.flink:flink-core</exclude>
                                    <exclude>org.apache.flink:flink-java</exclude>
                                    <!--                                                                    <exclude>org.apache.flink:flink-scala_2.10</exclude> -->
                                    <exclude>org.apache.flink:flink-runtime_2.10</exclude>
                                    <exclude>org.apache.flink:flink-optimizer_2.10</exclude>
                                    <exclude>org.apache.flink:flink-clients_2.10</exclude>
                                    <exclude>org.apache.flink:flink-avro_2.10</exclude>
                                    <exclude>org.apache.flink:flink-examples-batch_2.10</exclude>
                                    <exclude>org.apache.flink:flink-examples-streaming_2.10</exclude>
                                    <exclude>org.apache.flink:flink-streaming-java_2.10</exclude>

                                    <!-- Also exclude very big transitive dependencies of Flink WARNING:
                      You have to remove these excludes if your code relies on other versions of
                      these dependencies. -->
                                    <exclude>org.scala-lang:scala-library</exclude>
                                    <exclude>org.scala-lang:scala-compiler</exclude>
                                    <exclude>org.scala-lang:scala-reflect</exclude>
                                    <exclude>com.typesafe.akka:akka-actor_*</exclude>
                                    <exclude>com.typesafe.akka:akka-remote_*</exclude>
                                    <!--<exclude>io.netty:netty-all</exclude>-->
                                    <exclude>io.netty:netty</exclude>
                                    <exclude>commons-fileupload:commons-fileupload</exclude>
                                    <exclude>org.apache.avro:avro</exclude>
                                    <exclude>commons-collections:commons-collections</exclude>
                                    <exclude>org.codehaus.jackson:jackson-core-asl</exclude>
                                    <exclude>org.codehaus.jackson:jackson-mapper-asl</exclude>
                                    <exclude>com.thoughtworks.paranamer:paranamer</exclude>
                                    <exclude>org.xerial.snappy:snappy-java</exclude>
                                    <exclude>org.apache.commons:commons-compress</exclude>
                                    <exclude>org.tukaani:xz</exclude>
                                    <exclude>com.esotericsoftware.kryo:kryo</exclude>
                                    <exclude>com.esotericsoftware.minlog:minlog</exclude>
                                    <exclude>org.objenesis:objenesis</exclude>
                                    <exclude>com.twitter:chill_*</exclude>
                                    <exclude>com.twitter:chill-java</exclude>
                                    <exclude>commons-lang:commons-lang</exclude>
                                    <exclude>junit:junit</exclude>
                                    <exclude>org.apache.commons:commons-lang3</exclude>
                                    <exclude>log4j:log4j</exclude>
                                    <exclude>org.apache.commons:commons-math</exclude>
                                    <exclude>org.apache.sling:org.apache.sling.commons.json</exclude>
                                    <exclude>commons-logging:commons-logging</exclude>
                                    <exclude>commons-codec:commons-codec</exclude>
                                    <exclude>stax:stax-api</exclude>
                                    <exclude>com.typesafe:config</exclude>
                                    <exclude>org.uncommons.maths:uncommons-maths</exclude>
                                    <exclude>com.github.scopt:scopt_*</exclude>
                                    <exclude>commons-io:commons-io</exclude>
                                    <exclude>commons-cli:commons-cli</exclude>
                                </excludes>
                            </artifactSet>
                            <filters>
                                <filter>
                                    <artifact>org.apache.flink:*</artifact>
                                    <excludes>
                                        <!-- exclude shaded google but include shaded curator -->
                                        <exclude>org/apache/flink/shaded/com/**</exclude>
                                        <exclude>web-docs/**</exclude>
                                    </excludes>
                                </filter>
                                <filter>
                                    <!-- Do not copy the signatures in the META-INF folder. Otherwise,
                      this might cause SecurityExceptions when using the JAR. -->
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                            <!-- If you want to use ./bin/flink run <quickstart jar> uncomment
                  the following lines. This will add a Main-Class entry to the manifest file -->
                            <transformers>
                                <transformer
                                        implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>it.almaviva.wtf.mms.integratemobilitystatusevent.PassingEventProcess
                                    </mainClass>
                                </transformer>
                            </transformers>
                            <createDependencyReducedPom>false</createDependencyReducedPom>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerId>jdt</compilerId>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.eclipse.tycho</groupId>
                        <artifactId>tycho-compiler-jdt</artifactId>
                        <version>0.21.0</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>

        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.7.0</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <compilerId>jdt</compilerId>
                    </configuration>
                    <dependencies>
                        <dependency>
                            <groupId>org.eclipse.tycho</groupId>
                            <artifactId>tycho-compiler-jdt</artifactId>
                            <version>0.21.0</version>
                        </dependency>
                    </dependencies>
                </plugin>

                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.apache.maven.plugins</groupId>
                                        <artifactId>maven-assembly-plugin</artifactId>
                                        <versionRange>[2.4,)</versionRange>
                                        <goals>
                                            <goal>single</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore/>
                                    </action>
                                </pluginExecution>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.apache.maven.plugins</groupId>
                                        <artifactId>maven-compiler-plugin</artifactId>
                                        <versionRange>[3.1,)</versionRange>
                                        <goals>
                                            <goal>testCompile</goal>
                                            <goal>compile</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore/>
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>





Java 8, stream filter, reflect, NoSuchMethodException

I have this code

List<JComponent> myList = new ArrayList<>();
fillmyList(myList); //Some method filling the list
try{
    menuList.stream()
    .filter(m->m.getClass().getMethod("setFont", new Class[]{Font.class}) != null) //unreported exception NoSuchMethodException; must be caught or declared to be thrown
    .forEach(m -> m.setFont(someFont));
}
catch (NullPointerException |  NoSuchMethodException e) {} //exception NoSuchMethodException is never thrown in body of corresponding try statement

But, I have this error messages:

Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - exception java.lang.NoSuchMethodException is never thrown in body of corresponding try statement

How solve this?





How can I skip a generic argument?

Can somebody help me with this issue?

I have a some class, which I can't change. Like this:

public class SomeBaseClass<T1, T2>
    where T2 : SomeBaseClass<T1, T2>
{ }

And I've made a child class:

public class SomeConcretClass : SomeBaseClass<int, SomeConcretClass>
{  }

Now, I want to create a factory for instantiate this classes. Like this:

public class SomeFactory
{
    public T2 CreateSome<T1, T2>()
        where T2 : SomeBaseClass<T1, T2>, new()
    {
        return new T2();
    }
}

As you can see, I need to use the T1 generic argument only for using it in the where construction, but it don't use in the factory method body. I want to implement Create method, like this:

public T2 CreateSome<T2>()
        where T2 : SomeBaseClass<, T2>, new()
    {
        return new T2();
    }

But I can't do this, because of C# restrictions. Is there some way to implement method, like I've described before with the where construction and without using the generic argument, or there is only one way - using Create method with only one generic argument and use reflection in method body to instantiate concrete class. If the second option is true, could somebody help me with correct using reflection in this case?





How can I call Method.invoke with an arbitrary number of arguments?

I am building a system in which the user can type names of methods into a text file, and a java program will parse it, invoking methods in a separate class corresponding to the method name typed. The user also types all the arguments to the method in the file. Using Class.getMethods, I know the type and number of arguments that the desired method takes. I do not know how to call Method.invoke with the correct number of arguments given the number of arguments the method takes (which could be any number). Thanks in advance





Skipping classes from service description when compiling in one assembly

short story: I am trying to import, at runtime, a bunch of asmx services exposed from one server. I want to put those in one assembly and load it runtime. Everything is fine until i get to the moment where i compile the imported service descriptions as most of them have few classes that are multiplicated across the different service descriptions.

Some code:

    static void Main(string[] args)
    {

        IEnumerable<ServiceData> services = GetServices();
        List<CodeCompileUnit> codeCompileUnits = new List<CodeCompileUnit>();

        foreach (ServiceData service in services)
        {
            Console.WriteLine($"Doing {service.Name.ToUpper()}");
            WebClient webClient = new System.Net.WebClient();
            webClient.Credentials = new NetworkCredential("username", "password", "domainname");
            System.IO.Stream stream;

            try
            {
                stream = webClient.OpenRead($"{service.Endpoint}?wsdl");
            }
            catch (WebException we)
            {
                Console.WriteLine(we.Message);
                Console.WriteLine(we.InnerException?.Message);
                continue;
            }

            ServiceDescription description = ServiceDescription.Read(stream);

            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
            importer.ProtocolName = "Soap12"; // Use SOAP 1.2.
            importer.AddServiceDescription(description, null, null);

            importer.Style = ServiceDescriptionImportStyle.Client;

            importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

            CodeNamespace nmspace = new CodeNamespace($"Name.Space.{service.Name}");
            CodeCompileUnit unit1 = new CodeCompileUnit();
            unit1.Namespaces.Add(nmspace);

            try
            {
                ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
                if (warning == 0) // If zero then we are good to go
                {
                    codeCompileUnits.Add(unit1);
                }
            }
            catch (InvalidOperationException ioe)
            {
                Console.WriteLine(ioe.Message);
                Console.WriteLine(ioe.InnerException.Message);
            }

        }

        CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp" );

        string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };
        CompilerParameters parms = new CompilerParameters(assemblyReferences);
        parms.OutputAssembly = "Assembly.dll";

        CompilerResults results = provider1.CompileAssemblyFromDom(parms, codeCompileUnits.ToArray());

        if (results.Errors.Count > 0)
        {
            foreach (CompilerError oops in results.Errors)
            {
                Console.WriteLine("========Compiler error============");
                Console.WriteLine(oops.ErrorText);
            }
            throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window.");
        }
        else
        {

            Console.WriteLine("========Compiler error============");
            Console.WriteLine(results.PathToAssembly);
            Console.WriteLine(results.Output);

            //ToDo: Add the compiled assembly
            AppDomain.CurrentDomain.Load(results.CompiledAssembly.GetName());
        }

        var allTypes = AppDomain.CurrentDomain.GetAssemblies()
               .SelectMany(a => a.GetTypes().Where(c => c.IsClass && c.Namespace != null && c.Namespace.Contains(@"Name.Space"))).Select(t => new { Name = t.Name, Namespace = t.Namespace });

        //Assembly.GetExecutingAssembly().GetExportedTypes();

        foreach (var s in allTypes)
        Console.WriteLine($"{s.Namespace} => {s.Name}");

        Console.ReadLine();

    }

When I try to compile an assembly with

CompilerResults results = provider1.CompileAssemblyFromDom(parms, codeCompileUnits.ToArray());

I get few errors like this:

error CS0102: The type 'Name.Space.TypeNameGoesHere' already contains a definition for 'FielNameGoesHere'

So how do I force the compiler to ignore classes that are already in the namespace/assembly with the same name ?





How to set local variable memberExpression value

I want to get parameter original name and update its value. How can I do this?

public void SetMember<T>(Expression<Func<T>> memberExpression)
{
    var body = (MemberExpression)memberExpression.Body;
    var name = body.Member.Name; //text

    //can I set variable value here 
}

static void Main(string[] args)
{
    var text="test";
    SetMembere(() => text);
}





mardi 27 février 2018

(Vb.net) How to solve "Object reference not set to an instance of an object" error when using Reflection

everybody: How can I solve this "Object reference not set to an instance of an object" error when using Reflection. I'm a creating this "programme" to teach languages. Each Topic is in a separate form because it has many activities. To connect the list of activities to each topic (form) I'm trying to make this work: I'm trying to call one of these forms from a string which contains its name. I think the variable is already declared as a form. I also think the function helps the variable refering to a form. The name of the form is correct, too. So what do you think the problem is?

Private Sub Btn_EMPEZAR_Click(ByVal sender As System.Object, ByVal e As 
System.EventArgs) Handles Btn_EMPEZAR.Click

  Dim strCreatedFromButton As String = "Frm_The_Greetings" 
  Dim frm As New Form

  frm = DirectCast(CreateObjectInstance(strCreatedFromButton), Form)

  frm.Show() 'HERE I GET THE "Object reference not set to an instance of an 
  'object" error ***********

End Sub


Public Function CreateObjectInstance(ByVal objectName As String) As Object

  Dim obj As Object

  Try

    If objectName.LastIndexOf(".") = -1 Then
      objectName = [Assembly].GetEntryAssembly.GetName.Name & "." & objectName
    End If

    obj = [Assembly].GetEntryAssembly.CreateInstance(objectName)

  Catch ex As Exception
  obj = Nothing

  End Try
  Return obj

End Function





spring ReflectionUtils private field

I have a problem with java reflection. I use org.springframework.util.ReflectionUtils on my User class to "trim" white spaces from String attributes (let's not question my good practices now :).

The problem is, the attributes being private, that the reflection works in my DataLoader class but throws an exception when used in rest controller, which I think should be the right behavior. How come it works in the first example?

java.lang.IllegalStateException: Not allowed to access field 'username': java.lang.IllegalAccessException: Class TrimListener can not access a member of class User with modifiers "private"

User class

@Entity
@EntityListeners(TrimListener.class)
@Getter @Setter @NoArgsConstructor @AllArgsConstructor
public class User extends DatabaseObject {
    private String username;
}

TrimListener class

public class TrimListener<T extends DatabaseObject> {
    @PreUpdate
    @PrePersist
    public void trim (T object) {
        ReflectionUtils.doWithFields(object.getClass(), field -> {
            if(field.get(object) != null) {
                if(!field.get(object).toString().equals(field.get(object).toString().trim())) {
                    field.set(object, field.get(object).toString().trim());
            }
        }
    }, new TrimmableFieldFilter());
}

private class TrimmableFieldFilter implements ReflectionUtils.FieldFilter {
    @Override
    public boolean matches(Field field) {
        return (field.getType().equals(String.class));
    }       
}

DataLoader singleton, used to load sample data into DB. Here, the TrimmerListener works as it should, trimming username.

@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class DataLoader {
    @PostConstruct
    public void loadData() {
        User user = new User("vladko ");
        userRepo.save(user);
    }
}

Rest controller, which should just persist user. This version causes exception to be thrown, because accessing the private field of User through org.springframework.util.ReflectionUtils

@RestController
@RequestMapping("/user")
public class UserController extends DatabaseObjectController<User> {
    @PostMapping("/create")
    public ResponseEntity<UserDTO> createUser(@RequestBody(required = true) User user) {
        userRepo.save(user);
        return ResponseEntity.ok().body(user.toDTO());
    }
}

Thank you.





Can I use reflection to provide type arguments to a generic repository?

Goal

I would like to be able to count the number of times a specific PrimaryImageId is used within a number of different db entities.

Their classes each have a PrimaryImageId property and are adorned with a [HasPrimaryImage] attribute.

I may not know these classes in advance, so I want to use the [HasPrimaryImage] attribute to identify them, not hard code in the types.

I've Tried

I am using a generic repository method. But although it works when called with 'hard-coded' types:

GetCount<NewsItem>(x => x.PrimaryImageId == id);

...I can't get it to work when the type argument is provided from reflection.

var types = GetTypesWithHasPrimaryImageAttribute();
foreach(Type t in types)
{
    GetCount<t>(x => x.PrimaryImageId == id);
}

I've tried calling GetCount<t>(), GetCount<typeof(t)> and a few other silly things.

It appears that I can't call a generic method using a reflection generated type.

Question

Jon Skeet recommends using MakeGenericMethod in his answer, but I'm struggling to do that and wondering if that is overkill for my requirements. Is there an easier / better way to achieve what I'm after?



Db Entity Classes

[HasPrimaryImage]
public class NewsItem 
{
    public int PrimaryImageId { get; set; }

    // .. other properties
}


[HasPrimaryImage]
public class Product 
{
    public int PrimaryImageId { get; set; }

    // .. other properties
}

Generic Repository Method

public virtual int GetCount<TDataModel>(Expression<Func<TDataModel, bool>> wherePredicate = null)
    where TDataModel : class, IDataModel
{
    return GetQueryable<TDataModel>(wherePredicate).Count();
}

Get All Classes with HasPrimaryImage Attribute:

public static IEnumerable<Type> GetTypesWithHasPrimaryImageAttribute()
{
    var currentAssembly = Assembly.GetExecutingAssembly();
    foreach (Type type in currentAssembly.GetTypes())
    {
        if (type.GetCustomAttributes(typeof(HasPrimaryImageAttribute), true).Length > 0)
        {
            yield return type;
        }
    }
}   





How to modify the object value using the object name

How we can modify an Object Value when its path is available to us.

Consider below Person, Account and Department Class

// Person Class    
public class Person {
  private Integer id;
  private String name;
  private Integer age;
  private Account account;
  private List<Department> departments;
// setters and getters
}

// Account Class 
public class Account {
  private Integer id;
  private String accName;
  private String size;
// setters and getters
}

// Department Class
public class Department {
  private Integer deptId;
  private String deptName;
  private String deptSize;
// setters and getters
}

If there is a method which takes Person object as input and depending on the path i need to update the value of that same object then how it can be done?

public void method (Person person){
String path = "account.accName";
String newValue= "new value"

/*code to update the current value of accName with newValue*/
}

So here how will i update value of accName using path variable ? do i have to use reflection API ? if yes how ? or is there any other way to get it done. Kindly explain this at coding level as i am not able to get it .

Even for the list variable e.g i need to change deptName of second object in the list so for that

 String path = "departments[2].deptName";
 String newValue = "IT";

How this can be done?. Please provide your inputs.





How to compare two reflect.Value of method in golang

If I define a struct "A" and a method "Func" for ptr A

type A struct {}

func (a *A) Func() {}

Then I define another struct "C" embedded "A"

type C struct {
    *A
}

Then new a C

c := new(C)
CFunc := reflect.ValueOf(c).MethodByName("Func")
AFunc := reflect.ValueOf(c.A).MethodByName("Func")

I think CFunc is equal to AFunc,

but how can I compare CFunc with AFunc?

If I new a "A"

ANewFunc := reflect.ValueOf(new(A)).MethodByName("Func")

I think ANewFunc is not equal to AFunc,

and how can I compare ANewFunc with AFunc?





Spark - Registering Udf's through reflection

I have a object where I have written my Udf

object UdfBody {
def udfUpperCase() = { (s: String, sq: String) => s.concat(sq) }

Now this is in a different module, I want this udf to be used in my Spark processing. So, I have am using reflection to use this udf and trying to register it using this

def registerUdfFunc() = {
     val udfDf = DataFrameBuilder.getDataFrame("UDF_TABLE", "RDBMS", null, null, null)
     udfDf.collect.foreach { x =>
     registerDynamicUDF(x.getString(x.fieldIndex("className")), x.getString(x.fieldIndex("functionName")), x.getString(x.fieldIndex("udfName")));
}


private def registerDynamicUDF(objectName: String, udfFunction: String, udfName: String) = 
{
 val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader)
 val moduleSymbol = runtimeMirror.moduleSymbol(Class.forName(objectName))  
 var targetMethod = moduleSymbol.typeSignature.members.filter(x => 
 x.isMethod && x.name.toString == udfFunction).head.asMethod
 var function = runtimeMirror.reflect(runtimeMirror.reflectModule(moduleSymbol).instance).reflectMethod(targetMethod)()
 SparkSession.builder.getOrCreate().udf.register(udfName, function)
 } 

I have stored the Object name, UdfName(for registration), fucntionName in a table, from which I create dataframe and iterate through. Now when I Use

SparkSession.builder.getOrCreate().udf.register(udfName, function) 

it gives me error, saying cannot register udf with type anyand if I try to cast it to UserDefinedFunction it gives me classcast exception. What should I do, any Ideas?





lundi 26 février 2018

Calling a private method of other running app

I want to call a private method of com.android.bluetooth.BluetoothOppService StopListener() to prevent the system service BtOppService from accepting incoming bluetooth OPP request. I know how to call a method by instantiating a class myself and invoking methods using the instance, but I want to call the method using existing instance of a loaded process. This could be one great answer to my question, which asks the way to stop a system service.

Thank you in advance.





slf4j version incompatibility

I am trying to use the org.reflections library in my project. I am adding it to the list of my gradle dependencies, but when I run my code I get the following:

SLF4J: slf4j-api 1.6.x (or later) is incompatible with this binding.
SLF4J: Your binding is version 1.5.5 or earlier.
SLF4J: Upgrade your binding to version 1.6.x.

java.lang.NoSuchMethodError:  org.slf4j.impl.StaticLoggerBinder.getSingleton()Lorg/slf4j/impl/StaticLoggerBinder;

I understand this is because one of my dependencies is using internally a higher version of slf4j that is incompatible with the one that org.reflections is using.

I saw a suggestion to make sure the jar with the older version be included last. how can I do that in Gradle or is there another solutionH





How to use a reflect.Type to perform a type assertion

I know reflection is generally frowned upon in go but for my current purposes Im pretty sure it is the best solution.

Essentially my project is cli tool which will output an xml query based on incoming commands and return the corresponding result.

There is some boiler plate code for each command request where default values are populated and supplied values validated.

So I have a series of Command objects based on a Command struct as follows:

type Command struct {
    Name        string
    Request     interface{}
    RequestType reflect.Type
    Response    interface{}

    RegisterFunc func(parentCmd *cobra.Command, cmd *Command) error
}

For the most part I really don't care about the types of the request/response (just xml encode/decode). However I need to briefly cast it to a concrete type to validate with struct annotations So for example I might do something like this:

 var set bool
    if ccReq, set = command.Request.(*CreateCredentialRequest); !set {
        log.Fatal(errors.New("invalid request type"))
    }

    result, err := govalidator.ValidateStruct(ccReq)
    if err != nil {
        println("error: " + err.Error())
        os.Exit(1)
    }

However in an ideal would I would like to handle this generically for all commands, something like this:

var set bool
    if ccReq, set = command.Request.(command.RequestType); !set {
        log.Fatal(errors.New("invalid request type"))
    }

However this results in the error:

command.RequestType is not a type

So, how can I store the value of a type for a later type assertion





Convert sql server datetimeoffset to C# datetimeoffset or datetime

I have a column with datetimeoffset data type. For e.g.

2018-02-19 10:08:53.8060711 +00:00

I am trying to set this value to the C# property having the same data type.

In my application, I am using reflection to set the properties into the model (can't avoid reflection)

Here is the sample code -

Type propType = typeof(DateTimeOffset);
string value = "2018-02-19 10:08:53.8060711 +00:00";
// Failing here
propInfo.SetValue(model, Convert.ChangeType(value,propType));

Please note that the code is working for other datatypes. For e.g.

Type propType = typeof(bool);
string value = "true";
// This is working
propInfo.SetValue(model, Convert.ChangeType(value,propType));

If we can assign this value to DateTime instead of DateTimeOffset, that would also work for me





C# Cast object to generic interface with Type parameter

I want to cast an object as an generic custom Interface.

This is my interface:

public interface IContainer<T>
{
    IEnumerable<T> SaveToCache(IEnumerable<T> models);
}

I'm using this interface in a Serviceclass:

public class Manager()
{
    public Manager()
    {
        address = new Container<Address>(this);
        // more containers are constructed here...
    }

    private static Container<Address> address;
    public static Container<Address> Address => address;

    // here are more properties of Type Container<T>
}

Now I want to call the SaveToCacheAsync method dynamically like this:

private void SaveItems(IEnumerable<object> items, string typeName)
{
    object container = typeof(Manager)
        .GetRuntimeProperty(typeName).GetValue(null, null);
    var t = Type.GetType($"MyNameSpace.Models.{typeName}");

    // variant A - doesn't work, but makes clear what I want to do
    (container as IContainer<t>).SaveToCache(items);

    // variant B - doesn't work either
    var saveMethod = container.GetType()
        .GetRuntimeMethod("SaveToCache", new Type[] { Type.GetType($"System.Collections.Generic.List`1[{t.FullName}]") })
        .MakeGenericMethod(new Type[] { t });

    saveMethod.Invoke(container, new object[] { });
}

The project is a PCL, therefore I used GetRuntimeMethods.





dimanche 25 février 2018

Identify internal APIs used through reflection

I'm working on a legacy codebase, which was originally written in JDK 1.1.6. As a result there are a number of instances where internal JDK APIs are being used, especially in the RMI & Socket programming area.

I need to identify and create a list of these internal APIs used throughout my codebase.

I understand jdeps -jdkinternals can solve my purpose, and yes this command is helping me out to far an extent

Unfortunately, in places where the internal APIs are being used through reflection this approach isn't working for me.

Is there any (efficient) way other than the brute-force text search, that I can use in this scenario?





std::variant reflection. How can I tell which type of value std::variant is assigned?

I have a class called foo_t that has a member called bar which could be any one of the types std::string, int, std::vector<double>, etc. I would like to be able to ask foo_t which type bar has been assigned to. I decided to use std::variant.

I've written a solution, but I'm not sure if this is a good use of std::variant. I'm not sure if it matters, but I expect the list of types to possibly grow much bigger in the future. I made an enum class to store which type std::variant is assigned to. My first implementation also available on wandbox:

#include <iostream>
#include <variant>
#include <vector>
#include <string>

enum foo_kind_t {
  double_list,
  name_tag,
  number,
  unknown
};

template <typename val_t>
struct get_foo_kind_t {
  constexpr static foo_kind_t value = unknown;
};

template <>
struct get_foo_kind_t<int> {
  constexpr static foo_kind_t value = number;
};

template <>
struct get_foo_kind_t<std::string> {
  constexpr static foo_kind_t value = name_tag;
};

template <>
struct get_foo_kind_t<std::vector<double>> {
  constexpr static foo_kind_t value = double_list;
};

class foo_t {

public:

  foo_t(): kind(unknown) {}

  template <typename val_t>
  void assign_bar(const val_t &val) {
    static_assert(get_foo_kind_t<val_t>::value != unknown, "unsupported assignment");
    kind = get_foo_kind_t<val_t>::value;
    bar = val;
  }

  foo_kind_t get_kind() {
    return kind;
  }

  template <typename val_t>
  val_t get_bar() {
    if (get_foo_kind_t<val_t>::value != kind) {
      throw std::runtime_error("wrong kind");
    }
    return std::get<val_t>(bar);
  }

private:

  foo_kind_t kind;

  std::variant<
    int,
    std::string,
    std::vector<double>
  > bar;

};

template <typename val_t>
void print_foo(foo_t &foo) {
    std::cout << "kind: " << foo.get_kind() << std::endl;
    std::cout << "value: " << foo.get_bar<val_t>() << std::endl << std::endl;
}

int main(int, char*[]) {

    // double_list
    foo_t b;
    std::vector<double> b_val({ 1.0, 1.1, 1.2 });
    b.assign_bar(b_val);
    std::cout << "kind: " << b.get_kind() << std::endl;
    std::cout << "value: vector size: " << b.get_bar<std::vector<double>>().size() << std::endl << std::endl;

    // name_tag
    foo_t d;
    std::string d_val("name");
    d.assign_bar(d_val);
    print_foo<std::string>(d);

    // number
    foo_t c;
    int c_val = 99;
    c.assign_bar(c_val);
    print_foo<int>(c);

    // unknown
    foo_t a;
    std::cout << a.get_kind() << std::endl;

    return 0;
}

Is this a good way to do it? Is there a way having better performance? Is there a way that requires less code to be written? Is there a way that doesn't require C++17?





How to get type from different namespace than System in c#?

I would like to create types when being given only strings of their names. Here it's obvious:

Type t = System.Type.GetType("System.Double");

But when I try to get type from another namespace, like System.Drawing, the above method won't return the correct type. Working solution I've found:

Assembly foundAssembly = AppDomain.CurrentDomain.GetAssemblies().SingleOrDefault(assembly => assembly.GetName().Name == "System.Drawing");
Type t = foundAssembly.GetType("System.Drawing.Color");

However, it looks pure and I guess doing it costs some time (AppDomain.CurrentDomain has 22 assemblies in my case, but multiplied by 10000, it's something). So can we get it faster? I'm not searching for a solution like type = typeof(System.Drawing.Color);, because possibly I'll have to translate "System.Text.StringBuilder" to its type and so on...





Create a concrete object in a abstract class by using reflect methods

Suppose I have an abstract class called Model with the following static method:

 
public abstract class Model {
    ...
    public static List<Model> all() {
       ...
    }
    ...
}

And a concrete class the extends it:

public class Person exends Model {
...
}

So, is it possible to, using a static context, Person.all() return a list of Person and not of Model?

You know, by using a Template, or reflect methods such as getClass().getClassName() and getClass().getDeclaredMethod() and etc.

I am asking that because I have seen that in a PHP library and I am creating a similar library in java.





How to instantiate an inner class with reflection?

I would like to get the Constructor of a nested class so that I can instantiate it. I want this to be an inner class so that I can access variables from its outer class.

The code below throws a NoSuchMethodException with the inner prefix added:

package com.example

import android.util.Log

class ClassA {

    var iWantToUseThisFromTheInnerClass = "someValue"

    fun runThisToStart() {
        val classB = ClassB(InnerClassA::class.java)
        classB.doSomething()

    }

    inner class InnerClassA(text: String) {
        init {
            Log.d("ClassA", "Constructor invoked " + text)
        }
    }

}


package com.example

import java.lang.reflect.InvocationTargetException

class ClassB<T>(private var mModelClass: Class<T>) {

    val someText = "whatever"

    fun doSomething():T {
        try {
            val constructor = mModelClass.getConstructor(String::class.java)
            return constructor.newInstance(someText)
        } catch (e: NoSuchMethodException) {   // Throws this exception
            throw RuntimeException(e)
        } catch (e: InvocationTargetException) {
            throw RuntimeException(e)
        } catch (e: InstantiationException) {
            throw RuntimeException(e)
        } catch (e: IllegalAccessException) {
            throw RuntimeException(e)
        }
    }

}

Thanks





samedi 24 février 2018

Creating dynamic proxy on yet unknown subclasses

Let's say I have a class I don't own:

public class Base implements A,B,C {...}

Now, let's suppose that my framework allows injection of proxy Base classes like that:

@Unique //example annotation
@Inject
public Base someField; // results in a proxy that checks upon every 
                       // method call if Base "object" is still unique in some context

So far works good, but now a user that is using my library created a class:

public class Subclass extends Base {
    public void freeFun() {...}
}

And used this class for injection like:

@Inject
public Subclass someField; 

Now I'm sad. That not-very-nice user created a function in his subclass that is not an implementation of an interface method. I can still inject it as pure object thanks to reflection, but I can't create a proxy because these require interfaces to implement.

At this point, I don't really need to include his free method in the proxy handling, but I would still love to create a proxy that can be injected into such field.

Would something like that be possible?





getMethod returning method not found for com.google.gson.JsonObject

I have a method that is calling another method within a jar. The calling method is:

public String nextView(JsonObject jsonObj) throws IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
  System.out.println( "In next view" );
  Class jsonObjClass = new JsonObject().getClass();
  Class[] paramTypes = new Class[1];
  paramTypes[0] = jsonObjClass;
  System.out.println( jsonObjClass );
  Method[] m = jarClass.getDeclaredMethods();
  for (int i = 0; i < m.length; i++){
    String name = m[i].getName();
    Class[] params = m[i].getParameterTypes();
    System.out.print( name + " has the parameters of " );
    for(int j = 0; j < params.length; j++){
      System.out.print(params[j] + " ");
    }
    System.out.println( "" );
    Method thisMethod = jarClass.getMethod(name, params);
    if(name == "nextView"){
      System.out.println( "NEXT VIEW FOUND" );
      Method nextViewMeth = jarClass.getMethod(name, paramTypes);
    }
  }

Its output is:

In next view
class com.google.gson.JsonObject
main has the parameters of class [Ljava.lang.String;
handshake has the parameters of
nextView has the parameters of class com.google.gson.JsonObject
NEXT VIEW FOUND
No such method

As you can see I have been trying to figure out what is wrong with my calling method, I have tried looping through all the methods in the jar to figure out if "nextView" is declared. Which it is, and then I print its parameters which is the JsonObject.class from google's gson. But when I try to call get method with those parameters, I get a no method found exception.

What can I do?





Get Object type of class for ArrayList

So, I've tried to get object type of a given class to parse into ArrayList Example:

public class Util{
    public static void makeArray(String tag, Class<?> forClass) {
        ArrayList<?> list = new ArrayList();
    }
}

How can I replace <?> with forClass object type? So back in main method when I call

Util.makeArray("names", String.class);

It would create ArrayList<String> and if I say

Util.makeArray("ages", int.class);

It would resolve it to ArrayList<Integer>

And if it is not even done this way, show how.





SnakeYaml not using my setters

I am trying to parse a YAML file with SnakeYaml in Java and I am struggling to make it build my model objects via the setters. What I understood from the SnakeYaml doc, is that when you use object that follow the JavaBean rules, SnakeYaml uses reflection to find setters and use them to instanciate members.

I shrunk down the code to the following minimalist version, and it still does not work as I would expect:

This is my model object :

public class Report {

    private String MainSourceFile;

    public Report() {
        super();
    }

    public String getMainSourceFile() {
        return this.MainSourceFile;
    }

    public void setMainSourceFile(String mainSourceFile) {
        this.MainSourceFile = mainSourceFile;
    }
}

This is the code that parses the YAML file :

Constructor constructor = new Constructor(Report.class);

Yaml yaml = new Yaml(constructor);
Report report = null;

try (InputStream str = new FileInputStream(file);) {
    report = (Report) yaml.load(str);
} catch (FileNotFoundException e) {
    throw new ParsingErrorException( String.format("Error while reading export file %s : file not found", file.getAbsolutePath()), e);
} catch (YAMLException e) {
    throw new ParsingErrorException(String.format("Error while parsing export file %s", file.getAbsolutePath()), e);
} catch (IOException e1) {
    Activator.logWarning(String.format("Error while closing file %s", file.getAbsolutePath()));
}

And this is the YAML file :

---
MainSourceFile:  /home/user/workspace/project/ex.c

If I declare the MainSourceFile member as public, the parsing works (that's why it begins with an upper case). But I'd prefer not to let it public and furthermore, I would like to use the setter. I don't understand the reason why it does not use the setter : my Report class seems a legit JavaBean to me.

Is there anything else that I am missing?





vendredi 23 février 2018

How can I get properties of a Linq To SQL object without getting the navigation properties?

Expanding on this answer I came up with the following to dump a Linq to SQL query into a csv format:

Public Shared Function ObjectsToCsvData(ByVal objs As IEnumerable(Of Object)) As String
    If objs Is Nothing Then
        Throw New ArgumentNullException("obj", "Value can not be null or Nothing!")
    End If

    Dim sb As StringBuilder = New StringBuilder()
    Dim firstObj As Object = objs.First
    Dim t As Type = firstObj.[GetType]()
    Dim pi As PropertyInfo() = t.GetProperties(BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.Instance)
    For index As Integer = 0 To pi.Length - 1
        If Not pi(index).GetAccessors()(0).IsVirtual Then
            sb.Append(pi(index).Name)
            sb.Append(",")
        End If
    Next
    sb.Remove(sb.Length - 1, 1)
    sb.Append(vbCrLf)
    For Each obj As Object In objs
        For index As Integer = 0 To pi.Length - 1
            If Not pi(index).GetAccessors()(0).IsVirtual Then
                sb.Append(pi(index).GetValue(obj, Nothing))
                sb.Append(",")
            End If
        Next
        sb.Remove(sb.Length - 1, 1)
        sb.Append(vbCrLf)
    Next
    Return sb.ToString()
End Function

Problematically, this includes all the navigation properties as columns. Is there an easy way to exclude the related objects? I had hoped that the check for virtual properties would do it:

If Not pi(index).GetAccessors()(0).IsVirtual Then...

but I think I am confusing this with EF.





How to use reflect to recursively parse nested struct in Go?

I have a nested three layer struct. I would like to use reflect in Go to parse it (use recursive function). The reasons to use reflect and the recursive function are

  • can have various number of fields (but the first two fields are fixed)
  • the field types are not fixed.
  • The number of nested layers can be different (in this example only three layers. It can be many more)

Here are some codes. enter image description here

When I ran this, in the first layer I got "type: *entity.SacWebIS". However, in the second iteration/recursion, I got "type: *reflect.rtype" .

How to modify this code? Thanks.





Translate between KType and AnnotatedType

I have a simple TYPE_USE annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
public @interface Cool {
}

And the following sample Kotlin class:

class Item(
        id: Long? = null,
        var names: List<@Cool String> = emptyList())

Is there any way to extract the annotation using Java reflection?

Item.class.getMethod("getName").getAnnotatedReturnType() loses the annotations, same with getting the field.





How to get and invoke method with array parameters with Java reflection

I need to get and invoke the two following methods with reflection:

buildUniqueKeyFromColumnNames(Table table, String keyName, String[] columnNames)
buildUniqueKeyFromColumnNames(Table table, String keyName, String[] columnNames, String[] orderings, boolean unique)

I have tried the following, but without any luck:

Method buildUniqueKeyFromColumnNames1 = clazz.getDeclaredMethod("buildUniqueKeyFromColumnNames",
Table.class, String.class, String[].class);
Method buildUniqueKeyFromColumnNames2 = clazz.getDeclaredMethod("buildUniqueKeyFromColumnNames",
Table.class, JPAIndexHolder.class, UniqueConstraintHolder.class, String[].class, String[].class, Boolean.class);

This just resulted in NoSuchMethodException. I suspect that it has to something to do with the array parameters.

How to I get and invoke these two methods correctly using reflection?





Golang TypeOf without an instance and passing result to a func

Is it possible in go to get a "Type" without an instance? I've seen some examples that utilize reflect.TypeOf() but they all deal with an instance.

Below is a snippet of what I am attempting to do:

import (
    "net/http"
)

type ParamReader struct {
    // The request from which to extract parameters
    context *http.Request
}

// Initialize the ParamReader with a specific http request. This serves
// as the 'context' of our param reader. All subsequent calls will validate
// the params that are present on this assigned http.Request
func (p *ParamReader) Context(r *http.Request) {
    p.context = r
}

// Validate that a given param 's' is both present and a valid
// value of type 't'. A value is demeed valid if a conversion from 
// its string representation to 't' is possible
func(p *ParamReader) Require(s string, t Type) {
    // if context not have 's'
    //      addError('s' is not present)
    //      return


    if( t == typeof(uint64)) {
        // If not s -> uint64
        //      addError('s' is not a valid uint64)
    } else if (t == typeof(uint32)) {
        // ....
    } / ....
}

An example of my usage would be

func (h *Handler) OnRequest(r *http.Request) {
  h.ParamReader.Context(r)
  h.ParamReader.Require("age", uint16)
  h.ParamReader.Require("name", string)
  h.ParamReader.Require("coolfactor", uint64)
  h.ParamReader.Optional("email", string, "unspecified")
  h.ParamReader.Optional("money", uint64, 0)

  if h.ParamReader.HasErrors() {
    // Iterate or do something about the errors
  } else {
    coolness := h.ParamReader.ReadUint64("coolfactor")
    email := h.ParamReader.ReadString("email")
    money := h.ParamReader.ReadUint64(0)
  }
}

Note, after writing this out, I realize I could provide a "RequireUint64", "RequireUint32", etc.. perhaps that would be the Go way?





jeudi 22 février 2018

Not able to iterate collections if it saves in Any References in scala

I am creating a library where i need to identify changes between two objects of same type and store the old and new value in an object. Type could be primitive,Collections and object. Logic is that if the two objects passed of same type and if its primitive then directly it can go for (==,!=) operators to check for equality. But if its collections of same type then it needs to iterate its elements and check for equality. And if its an Object then it has to go through its all fields and identify its type and accordingly it should compare.

Snippet of the code :-

   def trackChanges(newRecord: Any, oldRecord: Any): Unit = {

        if (newRecord.getClass() == oldRecord.getClass()) {

            newRecord match {

                // Primitive Data Types......
            case u: Unit       => primitiveHandling(newRecord, oldRecord)
            case z: Boolean    => primitiveHandling(newRecord, oldRecord)
            case b: Byte       => primitiveHandling(newRecord, oldRecord)
            case c: Char       => primitiveHandling(newRecord, oldRecord)
            case s: Short      => primitiveHandling(newRecord, oldRecord)
            case i: Int        => primitiveHandling(newRecord, oldRecord)
            case j: Long       => primitiveHandling(newRecord, oldRecord)
            case f: Float      => primitiveHandling(newRecord, oldRecord)
            case d: Double     => primitiveHandling(newRecord, oldRecord)

            // Collections...
            case list: List[_] => collectionHandling(newRecord, oldRecord)
            case seq: Seq[_]   => collectionHandling(newRecord, oldRecord)

            // Object....
            case l: AnyRef     => objectHandling(newRecord, oldRecord)
            }
        }

        // Checks primitive data for changes
        def primitiveHandling(newRecord: Any, oldRecord: Any) {
            println("Primitive Handling")
            if (newRecord != oldRecord) {
                var auditlog = new AuditLog(oldRecord.toString(), newRecord.toString())
            }

        }

        // Check collection data for changes
        def collectionHandling(newRecord: Any, oldRecord: Any) {


        }

        // Check Object data for changes
        def objectHandling(newRecord: Any, oldRecord: Any) {

            val newfields: Array[Field] = newRecord.getClass().getDeclaredFields
                    val oldfields: Array[Field] = oldRecord.getClass().getDeclaredFields

                    for (i <- 0 until newfields.length) {

                        if (newfields(i).getType.isPrimitive) {

                            newfields(i).setAccessible(true)
                            oldfields(i).setAccessible(true)
                            primitiveHandling(newfields(i).get(newRecord), oldfields(i).get(oldRecord))
                        } else {
                            val t_new: Class[_] = newfields(i).getType
                                    val t_old: Class[_] = oldfields(i).getType

                                    if (t_new == classOf[Seq[_]] && t_old == classOf[Seq[_]]) {

                                        collectionHandling(newfields(i).get(newRecord), oldfields(i).get(oldRecord))
                                        for {
                                            newelement <- t_new.getName
                                            oldelement <- t_old.getName

                                        } trackChanges(newelement, oldelement)
                                        println("Sequence")
                                    }
                            if (t_new == classOf[List[_]] && t_old == classOf[List[_]]) {
                                for {
                                    newelement <- t_new.getName
                                    oldelement <- t_old.getName

                                } trackChanges(newelement, oldelement)
                                println("List")
                            }
                        }
                    }
        }

}

}





.NET Assembly.LoadFrom slower when PC is on a particular network

I have a .NET 3.5 C# app that loads plugins and searches for items using:

var myAssembly = Assembly.LoadFrom(c:\...\MyPlugin.dll)
Type [] Types = myAssembly.GetTypes();

When the PC is disconnected from or on most networks, these commands complete in milliseconds. But when the PC is connected to a particular user's network, they take 30 seconds each. How could a network cause these command to run more slowly when loading the same local file?

Thanks in advance for any thoughts you have.





Compile time reflections in Go

I am doing an inventory of all log statements in my Go application. Since the log statements will contain just variable names, a simple grep is not of use. I want to identify the variable "type" in each log statement and if its a struct, the field names in that struct. I want to write a script to do this.

Is it possible to extract such information using reflections or by any other means in Go?





Getting parameter type from proxy method and casting

I am using Castle DynamicProxy for creating a proxy for logging.

As a part of this I want to be able to grab the message ID (we are using RabbitMQ) to be able to log this as well.

The intercept is placed on a method that takes the following parameter:

ConsumeContext context

Within the context argument should be an object called Message which then contains the MessageId.

As the intercept is going over a network boundary, when we intercept the method and try to get the context argument, I believe because it's a generic it is coming out not as the right type and we therefore need to cast it. If I cast the parameter (invocation.Arguments[0] seen below) then I can see the Message object however it is a generic so I only know at run time what the type should be.

The image below shows the argument within the invocation (intercept) and the argument once the target method is invoked, i.e. one has the Message object one does not. If I cast the object then it works but I can't find anywhere to get the type.

castle issue

I've tried reflection with the following:

var invokeMethodParams = (((System.Reflection.MethodInfo)(invocation.Method))).GetParameters();
Type typetest = invokeMethodInfo [0].ParameterType;   

I then cast the object with typetest but it doesn't work it simply gives me the same kind of object I get in the first image, i.e. no Message object.





Cast to IEnumerable

This is a weird problem that I've stumbled upon, involving reflection:

I create a MyGenericType<T> at runtime where T is a runtime type:

object genType = Activator.CreateInstance(typeof(MyGenericType<>).MakeGenericType(runtimeType));

Then I need to pass it as an argument to another function which only accepts a IEnumerable<runtimeType>.

I can't use dynamic as MyGenericType only implements IEnumerable explicitly, not implicitly.

Is there anyway to cast to an IEnumerable<runtimeType>?





mercredi 21 février 2018

Refreshing JFrame after invoking method through Reflections

I have buttons that add strings with method names to the commands ArrayList. When a certain other (play) button is pressed, I want all the commands to be run. My current problem is that after clicking the play button, you can only see the end state after all the commands have been run. I would like to see the intermediate states - the state of the JFrame after each individual command has been run. All the methods call frame.repaint() and frame.revalidate(). I tried adding Thread.sleep in the loop, but it did not work.

playButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          try {
            for (String s : commands) {
              Method m = Robot.class.getMethod(s);
              m.invoke(null);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      });





Roslyn - how can I look up custom attributes for a class

I am trying to use Roslyn API (Microsoft.CodeAnalysis) for loading an assembly and looking up the custom attributes. Code I have so far is:

var assembly =  MetadataReference.CreateFromFile(tempFileName);
var compilation = CSharpCompilation.Create(null).AddReferences(assembly);
var assemblySymbol = (IAssemblySymbol)compilation.GetAssemblyOrModuleSymbol(assembly);

var globalNamespace = assemblySymbol.GlobalNamespace.GetAttributes();

But GetAttributes() is empty.

Can Roslyn even do this? Am I going about it the right way?

Thanks, VK





Matcherror in scala generic classtag

I want to create a map, where each key pairs with a value that has its own type. However, it throws a run time error scala.MatchError: Property[_] (of class scala.reflect.internal.Types$ExistentialType)

Anyone knows why? my guess is the scala type erasure?

case class Property[T: ClassTag](val value: T)

case class PropertyList(d: Map[String, Property[_]]) {
  def get[A: ClassTag](name: String): Option[A] =
    d.get(name)
      .flatMap { p =>
        p.value match {
          case o: A => Some(o)
          case _ => None
        }
               }
}

case class myObject ( 
                   propertyList: PropertyList =
                                  PropertyList(Map.empty[String, Property[_]]) 
    )





Xamarin.Android - typeof and GetType always return System.RuntimeType

I am developing a Xamarin.Android WebView application, and in an attempt to use Reflection to implement some AJAX methods, I have noticed that both Object.GetType and typeof always return System.RuntimeType.

This happens regardless of what I pass to them - it happens when I pass string, int, MyClass, etc to typeof, as well as when I call GetType on instances of these classes.

Minimum runnable code is trivial:

private class HybridWebViewClient : WebViewClient
{
    public static type Test() {
        Log.Debug("TypeDebug", typeof(string));
        Log.Debug("TypeDebug", typeof(bool));
        Log.Debug("TypeDebug", typeof(MyClass));
        Log.Debug("TypeDebug", "test".GetType());
        Log.Debug("TypeDebug", (34).GetType());
        Log.Debug("TypeDebug", (new MyClass()).GetType());
    }
}

All of the above print "System.RuntimeType". The equivalent code compiled using .NET prints the expected values - System.String, System.Bool, etc.

Has anyone else using Xamarin.Android encountered this? If so, is there a workaround? It is making the use of Reflection impossible for me, and I need it to pass information between JavaScript running in the WebView and the app itself





Get type from string termname

Basically I want to read untyped JSON into a type that's specified by a string. Pseudocode.

def getObject(json: Json, typeString: String): TermName(typeString) = extract[TermName(typeString)](json)





Invoke Event Handler via Reflection

I'm trying to invoke an event handler using reflection, but I keep getting the following error:

enter image description here

I'm assuming it's because of the arguments the function uses, but I'm really not sure. Code to get the method:

((Label)pControl).Background = m_pBrush;
string sControlName = ((Control)pControl).Name;
string sFuntionName = sControlName + "_MouseDoubleClick";

MethodInfo pMethod = this.GetType()?.GetMethod(sFuntionName);
pMethod.Invoke(((Label)pControl), null);

One of the functions it may find is public void lblShowLeaks_MouseDoubleClick(object sender, MouseButtonEventArgs e), so I tried creating a MouseButtonEventArgs object but I can't figure out how to grab the needed MouseDevice object needed by the constructor.

I've never used reflection before, so any help is appreciated.





Typescript - Get uninitialized properties after compilation

I am currently writing a wrapper around socket.io. Comming from a very object-oriented background, I want to implement the concept of Models in my framework/wrapper.

If you happen to know socket.io you might know that you get the data that is associated with a event as a parameter, now I have implemented a custom routing system where the handler of the route gets the data in an express.js like request object.

The idea is to have model classes that look something like this:

class XRequestModel
  @v.String({ message: 'The username must be a string!' })
  public userName: string;
}

And the route event might look something like this:

@RouteConfig({ route: '/something', model: XRequestModel })
class XEvent extends Route {
  public on(req: Request<XRequestModel>, res: Response) {
    // Handle Event
  }
}

And to complete the example here is how the request object might look like:

class Response<T> {
  public data: T;
}

Now generics in typescript are very limited, since the type information is removed after compilation, I can not use the generic Request parameter ( which is the type of the model ) to get metadata from the model - Metadata, in this case, is the validation decorator. To overcome this issue I give a reference of the Model class to the RouteConfig of the RouteEvent, which is internally used, and would allow me to create instances of the model, get the properties and so on...

The idea here is to give the handler of a route, a request object with pre-validated, typesafe data.

The thing holding me back from this, is the fact that unused properties, get removed after compilation by typescript, So i can not get the metadata of the model. Initializing the class-property would solve this:

class XRequestModel
  @v.String({ message: 'The username must be a string!' })
  public userName: string = '';
}

But I think this makes for some very verbose syntax, and I dont want to force the user of this wrapper to init all the model properties.

A implementation side-note:

The user of the framework has to register the classes to a 'main' class and from there I can get the Route-class via decorator reflection.

When I try to get the properties of the model without initialized properties - First model example.

// Here the route.config.model refers to the model from the RouteConfig
Object.getOwnPropertyNames(new route.config.model());
>>> []

Here is what I get with initialized properties:

Object.getOwnPropertyNames(new route.config.model());
>>> [ 'userName' ]

Here a link to the github repository: https://github.com/FetzenRndy/SRocket Note that models are not implemented in this repo yet.





java reflection: get list of classes in a package at compile to use at runtime

I have console application that do some reflection operations on list of classes (log field names, annotations, etc.).

Right now I create list of classnames by hand as strings in a file. I would love to be able to add project/package/configure path to build folder/etc. to my console project, build it and somehow use classnames got during compile in runtime.

Simple usecase: compile my app with a package, run on production site to check if every data class has proper database configuration.

Found this solution: https://dzone.com/articles/get-all-classes-within-package but it works during runtime and I prefer to get those names during compile time... is it possible? Or am I getting this wrong?





mardi 20 février 2018

EntityFramework LINQ Order using string and nested reflection

I saw already some of the similar questions, but cannot find an anwser how to solve this problem.
I want to have a possibility to order collection using string as property name.

Model:

User { string FullName; User SuperiorUser }

And I want to make a call like this:

DbSet.Order("SuperiorUser.FullName", Asc/Desc)...

My below functions work for a Order("FullName", Asc/Desc), but dont when I want to go deeper.

public static IOrderedQueryable<T> Order<T>(this IQueryable<T> source, string propertyName,
    ListSortDirection direction = ListSortDirection.Ascending)
{
    return ListSortDirection.Ascending == direction
        ? source.OrderBy(ToLambda<T>(propertyName))
        : source.OrderByDescending(ToLambda<T>(propertyName));
}

private static Expression<Func<T, object>> ToLambda<T>(string propertyName)
{
    var parameter = Expression.Parameter(typeof(T));
    var property = Expression.Property(parameter, propertyName);

    return Expression.Lambda<Func<T, object>>(property, parameter);
}

So I made it look a little bit like this

private static Expression<Func<T, object>> ToLambda<T>(string propertyName)
{
    var propertyNames = propertyName.Split('.');
    var type = typeof(T)
    ParameterExpression parameter;
    MemberExpression property;
    for (var propName in propertyNames)
    {
        parameter = Expression.Parameter(type);
        property = Expression.Property(parameter, propName);
        type = property.Type;
    }
    return Expression.Lambda<Func<T, object>>(property, parameter);
}

But this unfortunately returns error The parameter '' was not bound in the specified LINQ to Entities query expression. What am I missing?





Scala reflection Generic TypeArgs exposure

I seem to be stuck behind generic type parameters when trying to expose the case accessors in a case class via reflect.

Say I have this:

case class test(
  propA: Option[Int],
  propB: String
)

I can spit out the model of the test case class but am stuck with this result:

{ "subject" : "test",
  "model" : [
    {"field" : "propA", "type" : "A"},
    {"field" : "propB", "type" : "String"}
  ]
}

The entries come in as java Fields and I'm using the runtimeMirror to get a ClassSymbol for the class as provided via Field.getType.

val parameterizedType = runtimeMirror(field.getType.getClassLoader).classSymbol(field.getType)

Then I'm trying to use the selfType to get at the typeArgs but as shown above instead of getting Int I'm getting A and it has me stuck because I'm not as familiar with scala reflect. The type exposure is done with the following line:

parameterizedType.selfType.dealias.typeArgs.map(_.toString).mkString

I tried to use only Scala reflect to expose the field but the class that I'm inspecting is sometimes a Java class and I ran into issues exposing the fields that way.

Additionally, I've been able to expose the full type path but it still hides the parameterized type:

... "propA", "type" : "scala.Option.A"

Any help is appreciated!





How to convert fieldinfo to it's actually class object? using C#

i need to create program that navigate an object structure and print the structure of any “struct” provided as an argument.

These "structs" are defined as follows:

  • They have only public attributes
  • Each attribute can be of the following types:
    • “Structs”
    • Primitive (e.g. int), primitive wrapper (e.g. Integer) or String

the problem is when i'm trying to print data member which is a class or struct. i'm trying to to write a recursive function that gets an object and check each field in the object: if it's a class them i send again the curr field to the same function. else i print the value of the field.

this is my code. but when i send the fieldInfo to the function the code line: ---> Type objType = i_obj.GetType();

is getting me the next value: object.GetType returned {Name = "RtFieldInfo" FullName = System.Reflection.RtFieldInfo"} System.RuntimeType

    public static void getObj(object i_obj)
    {
        Type objType = i_obj.GetType();

        FieldInfo[] objField = objType.GetFields();

        foreach (FieldInfo member in objField)
        {
            Type memberType = member.FieldType;

            if(memberType.IsClass)
            {                    
                getObj(member);
            }

            else
            {
                Console.WriteLine(member.Name + " : " + member.GetValue(i_obj));
            }

        }
    }

how can i get the real object from fieldInfo ??





Modifying final static variable within final public class Java

I have a quick question regarding modifying a final public class. Based on some researches, it seems like final public class cannot be inherited or implemented. My goal is to change one final static variable within this final public class.

class name is: public final class Utils

private static final Set<String> DISALLOWED_HEADERS_SET = Set.of(
    "authorization", "connection", "cookie", "content-length",
    "date", "expect", "from", "host", "origin", "proxy-authorization",
    "referer", "user-agent", "upgrade", "via", "warning");

I want to get rid of "authorization" field from this DISALLOWED_HEADERS_SET. Is there any ways to doing this?

I heard reflection is one way to modify classes. This is a link to a github that seems to reveal what's inside of the class

Thank you in advance for your time and help





Do we have to safe guard Scala Object (Singleton Instances) against Reflection attacks like we have to do in Java?

Is it possible to create a new instance of a Object Class in Scala using both Scala and Java reflection API?

If yes, then what should be the practice that one should follow to safe guard against this.

If no, then a brief insight about how Scala stop this attack would be very helpful.

Thanks in advance.

I'm a Java developer, currently learning Scala.





C# Bind dynamic Function to Event

I have a really weird problem here. I Want to bind a function to a Event. But the Event and the Function to be bound are only compatible through a proxy function and at start I have just the names as String.

At first: This is the delegate and the Event:

    public delegate void ControllerInteractionEventHandler(object sender, ControllerInteractionEventArgs e);
[...]
public class VRTK_ControllerEvents : MonoBehaviour{
[...]
        public event ControllerInteractionEventHandler TriggerPressed;
[...]

Then I have This function wich I want to be called:

public void Export_LoadObject(string guid, string PrefabName, string sender = null){[...]}

Normally the Binding wouldnt be a Problem. Now lets see what we have:

    private void addEventBinding(string obj, string component, string eventName, string functionName, string param){
    GameObject go = m_Instance_Id.getObject<GameObject>(obj);

            dynamic comp = go.GetComponents<Component>().Where(x => x.GetType().Name.Equals(component)).ToArray()[0];
            EventInfo eventInfo = comp.GetType().GetEvent(eventName);

            Type[] handlerArgs = { typeof(object), typeof(ControllerInteractionEventArgs) };
            method = new DynamicMethod("EventMethod", typeof(void), handlerArgs);
            Type[] paramArgs;
            paramArgs = new Type[param.Split(',').Length];
            for (int i = 0; i < paramArgs.Length; i++)
            {
                paramArgs[i] = typeof(string);
            }


            MethodInfo calling = typeof(WebApi).GetMethod("Export_" + functionName, paramArgs);

            ILGenerator il = method.GetILGenerator(256);
            for (int i = 0; i < paramArgs.Length; i++) {
                FieldInfo f = typeof(OpCodes).GetField("Ldarg_" + i);
                OpCode code = (OpCode)f.GetValue(null);
                il.Emit(code);
            }
            il.EmitCall(OpCodes.Call, calling, null);
            il.Emit(OpCodes.Ret);



            RegisterEventDelegate handler = (RegisterEventDelegate)method.CreateDelegate(typeof(RegisterEventDelegate));
            eventInfo.AddEventHandler(comp, handler);

As u can see I have to find everything at runntime and I never used ILGenerator bevore.

I get the following error:

InvalidProgramException: Invalid IL code in (wrapper dynamic-method) object:EventMethod (object,VRTK.ControllerInteractionEventArgs): IL_0002: ldarg.2

System.Delegate.CreateDelegate (System.Type type, System.Object firstArgument, System.Reflection.MethodInfo method, System.Boolean throwOnBindFailure, System.Boolean allowClosed) (at <9c9f068c46c64ffd91fda7af157b4d15>:0) System.Delegate.CreateDelegate (System.Type type, System.Reflection.MethodInfo method, System.Boolean throwOnBindFailure) (at <9c9f068c46c64ffd91fda7af157b4d15>:0) System.Delegate.CreateDelegate (System.Type type, System.Reflection.MethodInfo method) (at <9c9f068c46c64ffd91fda7af157b4d15>:0) System.Reflection.Emit.DynamicMethod.CreateDelegate (System.Type delegateType) (at <9c9f068c46c64ffd91fda7af157b4d15>:0) (wrapper dynamic-method) System.Object:CallSite.Target (System.Runtime.CompilerServices.Closure,System.Runtime.CompilerServices.CallSite,object,System.Type) System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet] (System.Runtime.CompilerServices.CallSite site, T0 arg0, T1 arg1) (at <11c1c8f1ba1046b191f565f88728429e>:0)

I didnt really get whats wrong about it, can anyone help?