jeudi 30 avril 2015

cannot get package name if object class is array on field using java reflection

I have some problem.

class example{
     JLabel[] label=new JLabel[3];
}

so, i have tried reflection :

Class cls=Class.forName("example");
Field[]f=cls.getDeclaredFields();
for(field : f)
     field.getType().getPackage();

the result is null





c# WebRequest HttpBehaviour error

guys. I wrote some code:

        this.req = (HttpWebRequest)WebRequest.Create(this._urlNBKIMain);
        this.req.Accept = this._accept;
        this.req.Headers.Add(this._acceptLanguage);
        this.req.UserAgent = this._userAgent;
        this.req.Host = this._hostNBKI;
        this.req.KeepAlive = this._keepAlive;
        this.req.AutomaticDecompression = (DecompressionMethods.GZip | DecompressionMethods.Deflate);
        this.req.CookieContainer = this.cookieContainer;
        ServicePoint servicePoint = this.req.ServicePoint;
        PropertyInfo property = servicePoint.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
        property.SetValue(servicePoint, 0, null);
        this.res = (HttpWebResponse)this.req.GetResponse();

But, I got runtime error:

System.ArgumentException: It is not possible to convert an object of type "System.Int32" to type "System.Net.HttpBehaviour". in System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast) in System.RuntimeType.CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr) in System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig) in System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) in System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) in System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) in System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index) in CheckNBKI.GetMainFormNBKI()

Help me, please.





reflect: How to get the name of a struct field?

type User struct { Name string }

func test(o interface{}) {
    t := reflect.TypeOf(o)
    fmt.Println(t)
}

u := &User{"Bob"}
test(u.Name) // prints "string", but I need "Name"

Is this possible in Go? I want to have as few "magic strings" as possible, so instead of having

UpdateFields("Name", "Password")

I'd much rather use

UpdateFields(user.Name, user.Password)





JUnit Test Case via Private Method in Dijkstra Algorithm

I'm trying to figure out the best way to implement a test case for a class exercise. My class exercise provides the known bug and with this I should write a test case for it to fail, and thus find the bug. It involved using the Dijkstra Algorithm.

This is the correct version of the provided code:

private int getNodeWithMinimumDistanceFromUnsettled()
{
    int min;
    int node = 0;

    Iterator<Integer> iterator = unsettled.iterator();
    node = iterator.next();
    min = distances[node];
    for (int i = 1; i <= number_of_nodes; i++)
    {
        if (unsettled.contains(i))
        {
            if (distances[i] <= min)
            {
                min = distances[i];
                node = i;
            }
        }
    }
    return node;
}

The known bug in a separate version is as follows:

if (unsettled.contains(i))
        {
            if (distances[i] > min)
            {
                min = distances[i];
                node = i;
            }
        }

and here is the JUnit Test case I'm using to find it. I'm trying to access this method with Java Reflection and then try to assert whether the node returned is equal to the node is actually the larger distance.

Here is my test case:

int[][] adjacency = { { 0, 0, 0, 0, 0 },
                          { 0, 0, 9, 10, 0 },
                          { 0, 9, 0, 0, 0 },
                          { 0, 5, 4, 0, 2 },
                          { 0, 5, 4, 3, 0 },
                                             }; 
 Dijkstra d1 = new Dijkstra(4);
 d1.dijkstra_algorithm(adjacency, 1);



    /*
    try {

    nodeMethod =   Dijkstra.class.getDeclaredMethod("getNodeWithMinimumDistanceFromUnsettled");

    } catch (NoSuchMethodException e) {
        System.out.println(e.getMessage());
    }

    nodeMethod.setAccessible(true);

    try {   
            node = (int) nodeMethod.invoke(d1);
            System.out.println("min node is: " + node);     
    } catch (IllegalAccessException | InvocationTargetException e) {
            System.out.println(e.getMessage());
    }

    assertEquals(node, 0); 
    */

When I run the test, it doesn't seem to do anything as I get no output. I feel like I'm overthinking this. Is there an easier way to find this bug without using java reflection?





GetMethod overload returns null

I want to get a method from specific interface, but it can be in multiple interfaces. I write this code:

private static Expression<Func<T, T, int>> CreateCompareTo<TProperty>(MemberExpression expression, Expression<Func<T, T, int>> result) where TProperty : IComparable<TProperty>, IComparable
{
    var methodInfo = typeof(TProperty).GetMethod("CompareTo", new[] { typeof(IComparable<TProperty>), typeof(IComparable) });
    ...

MSDN

An array of Type objects representing the number, order, and type of the parameters for the method to get.

So I expect that it will search method through IComparable<T>, and, if didn't found, will search it in non-generic IComparable. But it doesn't. Well, now I rewrite it:

private static Expression<Func<T, T, int>> CreateCompareTo<TProperty>(MemberExpression expression, Expression<Func<T, T, int>> result) where TProperty : IComparable<TProperty>, IComparable
{
    Type t = typeof(TProperty);
    var methodInfo = t.GetMethod("CompareTo", new[] { typeof(IComparable<TProperty>) }) ?? t.GetMethod("CompareTo", new[] { typeof(IComparable) });
    ...

And now it works.

Why first option is not working?





mercredi 29 avril 2015

to flip an image across a diagonal line y=x

I have an image of size 256x256 and it is divided into 58081 overlapping blocks of size 16x16. I flipped each and every block vertically and horizontally using flipdim(image block, dimension)function. Is there any function to flip every block across the main diagonal line y=x?





Method interceptor for a final quantified method

I'm trying some method interceptor which can intercept a method in a class. I tried using cglib, bytebuddy. I cannot use normal Java proxy class, since it is a class. Is there any way to intercept my final method. Here is, what I've tried so for.

//My Target class,

public class Hello {
    public final  String sayHello(){
    //return lower case hello
    return "hello";
    }
}

//Main Application

public class InterApp {
    public static void main(String[] d) throws Exception {
        new InterApp().loadclassDD();
    }

    public void loadclassDD() throws Exception {
       //Byte-buddy
        Hello helloObject1 = new ByteBuddy()
                .subclass(Hello.class)
                .method(named("sayHello"))
                .intercept(MethodDelegation.to(LoggerInterceptor.class))
                .make()
                .load(getClass().getClassLoader(),
                        ClassLoadingStrategy.Default.WRAPPER).getLoaded()
                .newInstance();
        System.out.println(helloObject1.sayHello());
       //CGLIB
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Hello.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object arg0, Method arg1, Object[] arg2,
                    MethodProxy arg3) throws Throwable {
                System.out.println("method name " + arg1.getName());
                return arg3.invokeSuper(arg0, arg2).toString().toUpperCase();
            }
        });
        Hello proxy = (Hello) enhancer.create();
        System.out.println(proxy.sayHello());
    }
}

//LoggerInterceptor - Byte-buddy implementation

public class LoggerInterceptor {
public static String log(@SuperCall Callable<String> zuper)throws Exception {
    System.out.println("Method intercepted");
    return zuper.call().toUpperCase();
}
}

If I remove the final quantifier from the method both are working(Providing upper case HELLO as output). What is reason for this.? Is there any way to achieve this? Correct me, if my understanding is wrong.





Does calling a method on a dynamic object basically do GetMethod().Invoke()?

The title is basically my question. Under the covers does the last line of this:

Type xmlCodecType = typeof(XmlCodec<>).MakeGenericType(typeof(SomeObjectProperty));
dynamic xmlCodec = Activator.CreateInstance(xmlCodecType);
xmlCodec.ReadCollection(xmlCodec.GetCollectionName());

basically do this:

MethodInfo method1 = xmlCodec.GetType().GetMethod("ReadCollection");
MethodInfo method2 = xmlCodec.GetType().GetMethod("GetCollectionName");
method1.Invoke(xmlCodec, new obj[] { method2.Invoke(xmlCodec, null) });

when executed??

Most of what I have written is using the reflection method because it is what I was used to and just feels a bit more 'catch errors during compile time' with the passing of the write types and objects and such. Dynamic is a bit more hands off. However reflection can be harder to read/follow at times whereas while dynamic is not always a keyword in a language, it is common concept across most of them.





How do you programmatically get a list of all common parameters?

Powershell Cmdlets inherit a bunch of common parameters. Some cmdlets I write end up with predicates that depend on which parameters are actually bound. This often leads to filtering out common parameters which means you need a list of common parameter names.

I also expect there to be difference in the list of common parameters from one version of powershell to another.

All of this boils down to this question:

How do you programmatically determine the list of common parameters?





How to get generic field type (string representation) with help reflection - Java?

There are some fields:

public class Class1 {
    private Map<String,Integer> field1 = new HashMap<String,Integer>();
    private int someField = 1;
    private int[] myIntArray = new int[]{1,2,3};
    private List<ArrayList<String>> words = null;
    private ArrayList<String>[] group = (ArrayList<String>[])new ArrayList[4];
    private List<List<List<ArrayList<List<List<String>>>>>> lists = null;
}

Is there a simple way to get string representation of each of these (and generally any) types?





Java: Accessing private field via reflection ()

Junior in Java; using reflection is possible to access private fields (not asking how, Question 1 and Question 2) Ok.

My questions are related with the nature of this behaviour.

  1. Is there any limitation? Can I access any field of any .class I come across?
  2. During my code, once you set the visibility of a field to lets say "public", is it changed forever or just up to the end of the context (method, if, for...)? Code below
  3. Is it ok for everybody? I mean, Seniors programmers of StackOverflow, is it a security breach?

Code:

private Object foo(Object obj) {
  Field f = obj.getClass().getDeclaredField("field"); 
  f.setAccessible(true);
  return (Object) f.get(obj);
}
private Object goo(Object obj) {
 // IS obj.field accesible in this context?
}





get @hide property via reflection

I have use follow code get localDisplayMetrics .

DisplayMetrics localDisplayMetrics = new DisplayMetrics();
((WindowManager) getSystemService("window")).getDefaultDisplay()
                .getMetrics(localDisplayMetrics);

I want to get localDisplayMetrics.noncompatWidthPixels.Can I get it via reflection?





Call method with custom attribute with 2 or more identifiers through reflection

Say I have the following method with my custom attribute ApprovalIdentifierAttribute:

// FormState is an enum
// WorkflowType is an enum
// There will be multiple methods like this, where the FormState is Draft
// but the WorkflowType is different.
[ApprovalIdentifier(FormState.Draft, WorkflowType.PriceApproval)]
public static void SetDraftReviewers()
{
    SetDraftReviewer(new[] {"Lucy", "Stan"});
}

I want to be able to have a collection of all methods with this attribute and then use FormState & WorkflowType to identify which method I want to invoke.

How would I call the method through reflection on this condition?
Is it possible?





Swift: Check if class conforms to protocol for getter

I was wondering if it is possible to check if a class conforms to a protocol in swift.

I have an EntityObject class, which contains some basic functionality in Java I'd make it abstract but since swift doesn't do abstraction I'm running it like this.

I also have an Entity Protocol which requires a getter for a path property (which does not really exist but always returns the path in our API).

Now in the EntityObject class which is always extended (otherwise you get fatalError's in your face). I want to get this path but EntityObject does not conform to the Entity Protocol but it's children do in most cases.

example path getter:

class var path:String {get { return "blog/{blogId}/comments" } }

The getters do not show up in the Mirror using reflect() probably because it's a class(static) var, and I tried something like:

if let entity = self as? Entity {
    return entity.path
}

But this returns an instance of Entity (I guess) since I'm not allowed to use the path here or see any of the options.

Anyone know if I could do this generically?





Maven shade plugin + JAXB RI

I have encountered the following problem while trying to use maven shade plugin with the code that uses JAXB.

I would like to pack my code into uber-jar with all dependencies shaded, so I include the following into pom.xml:

<relocations>
<relocation>
<pattern>com</pattern>
  <shadedPattern>quase.com</shadedPattern>
</relocation>
<!-- ... other top-level patterns for external dependencies -->
<relocation>
  <pattern>org</pattern>
  <shadedPattern>quase.org</shadedPattern>
  <excludes>
    <exclude>org.aau.**</exclude> <!-- my own code is not shaded -->
  </excludes>
</relocation>
</relocations>

The problem is that my code uses JAXB (default rt.jar implementation), so after calling the initialization:

SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature("http://ift.tt/Qb9Hvl", false);

JAXBContext jaxbContext = JAXBContext.newInstance(ADOXML.class);
ADOXML adoxml = (ADOXML) jaxbContext.createUnmarshaller().unmarshal(
    new SAXSource(spf.newSAXParser().getXMLReader(),
        new InputSource(String.valueOf(new File(fileName).toURI()))));

I got the following error:

[java.lang.ClassNotFoundException: quase.com.sun.xml.internal.bind.v2.ContextFactory]
        at quase.javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:241)
        at quase.javax.xml.bind.ContextFinder.find(ContextFinder.java:455)
        at quase.javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:652)
        at quase.javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:599)
        at quase.org.aau.quase.quontology.builder.QuBuilderUtils.getModelFromFile(QuBuilderUtils.java:185)
        at quase.org.aau.quase.quontology.ontology.QuOntologyOWLAPI.createOntologyFromModel(QuOntologyOWLAPI.java:574)
        at org.aau.quase.quontology.builder.QuSiteOntologyBuilder.main(QuSiteOntologyBuilder.java:43)
Caused by: java.lang.ClassNotFoundException: quase.com.sun.xml.internal.bind.v2.ContextFactory
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at quase.javax.xml.bind.ContextFinder.safeLoadClass(ContextFinder.java:573)
        at quase.javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:239)
        ... 6 more

It seems that the rt.jar implementation of JAXB (which includes com.sun.xml.internal.bind.v2.ContextFactory) is not getting shaded with the rest of the dependencies because it is not available to me separately - only as a part of rt.jar so it is not included into uber-jar. But the code which calls it got modified and expects the shaded version i.e. quase.com.sun.xml.internal.bind.v2.ContextFactory.

I tried to do two things to resolve this issue:

  1. I have tried to explicitly un-shade the offending class:

    <relocation>
    <pattern>com</pattern>
    <shadedPattern>quase.com</shadedPattern>
    <excludes>
        <exclude>com.sun.xml.internal.bind.v2.**</exclude>
    </excludes>
    </relocation>
    
    

    but this seemed to have little effect, as now I got an error in this form

    [java.lang.ClassNotFoundException: quase/com.sun.xml.internal.bind.v2.ContextFactory]
            at quase.javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:241)
     ... 
    
    

    so now instead of missing the class in a shaded package i.e. quase.com.sun... it misses the class in a kind of directory i.e. quase/com.sun... This seems to be a problem with the reflection handling in the shade plugin, as the reflection-based calls got modified to expect shaded versions regardless of excluding the classes being called from shading.

  2. I have tried to grab the complete control over JAXB version I am using by putting the non-rt.jar versions of JAXB (jaxb-api-2.2.11.jar and jaxb-impl-2.2.11.jar) into "endorsed" directory and making maven know about it:

    <compilerArguments>
    <endorseddirs>c:/java/jdk1.8.0_31/lib/endorsed</endorseddirs>
    </compilerArguments>
    
    

    but this still has no effect for some reason - the error is the same as above so the code still expects the rt.jar version of the JAXB code to be called (as non-rt versions of JAXB do not include com.sun.xml.internal.bind but instead com.sun.xml.bind).

What am I doing wrong? Any suggestions?





How to get all namespace in project by assembly? [duplicate]

This question already has an answer here:

I want get all namespace in main project by method assembly.(Not all aseembly)

I read below question but not useful.

Getting all types in a namespace via reflection

for example

class in Assembly:

namespace test
{
    public class Class1
    {
        public string[] AllNameSpace()
        {
            return Assembly.GetExecutingAssembly().GetTypes().Select(x => x.Namespace).ToArray();
        }
    }
}

code in main project:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var util=new Class1();
            Console.WriteLine(string.Join(",",util.AllNameSpace()));//return test
            Console.ReadKey();
        }
    }
}

return "test" But I want contain ConsoleApplication1 namespace.





Dynamic code embedding; just like working with immediate window [duplicate]

This question already has an answer here:

Is it possible to write basic strings and run them as c# codes as if using immediate window when debug mode. Well, I'm looking for without using CSharpCodeProvider. It should just trust on my code that I ll use my existing objects.

For example

  static void Main(string[] args)
    {

        string code = "Console.WriteLine(\"Hello world!\");";
        ExecuteCode(code);

    }

Kind regards.





How to get an "extern const int" value by its name

I would like to get the int value of my extern const by its name.

For example in my .h file:

extern const int MY_INT_CONST;

In my .m file:

const int MY_INT_CONST = 0;

What I want:

- (void) method {
    int i = [getMyConstantFromString:@"MY_INT_CONST"];
}

How can I do that?

I searched in RunTime api and I did not find anything.





C# - How to get all namespace in main program by method assembly?

I want get all name namespace in main project by method assembly.

I read below question but not useful.

Getting all types in a namespace via reflection





mardi 28 avril 2015

How to Perform Contains Query On All Properties of an Entity Framework Model

I am trying to write something that will do a "Contains" query on all properties of an entity framework model.

I am able to do the following for example with no issues:

var students = db.Students.AsQueryable();
var test = students.Where(x => x.ID.ToString().ToLower().Contains("1"));

I found a code sample online that does what I want, but it's old and I am getting an error that I can't seem to resolve.

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

I have read up on this error, but as you see above ToString is perfectly valid even when using an IQueryable (which is required in my case because I don't want to post filter the data).

I have the following method that runs without errors but then when you convert ToList() it fails:

 private Expression<Func<T, bool>> getSearchExpression()
        {
            string search = _request.Search.Value;

            var filterableColumnIds = new HashSet<string>(_request.Columns.Where(x => x.Searchable).Select(x => x.Data));
            var filterProperties = _properties.Where(x => filterableColumnIds.Contains(x.Name)).ToList();

            //  When no filterProperties or search term(s), return a true expression
            if (string.IsNullOrEmpty(search) || !filterProperties.Any())
            {
                return x => true;
            }

            var paramExpression = Expression.Parameter(typeof(T), "val");
            Expression compoundOrExpression = Expression.Call(Expression.Property(paramExpression, filterProperties[0]),"ToString", null);
            Expression compoundAndExpression = Expression.Call(Expression.Property(paramExpression, filterProperties[0]), "ToString", null);
            MethodInfo convertToString = typeof(Convert).GetMethod("ToString", Type.EmptyTypes);

            //  Split search expression to handle multiple words
            var searchTerms = search.Split(' ');

            for (int i = 0; i < searchTerms.Length; i++)
            {
                var searchExpression = Expression.Constant(searchTerms[i].ToLower());

                //  For each property, create a contains expression
                //  column => column.ToLower().Contains(searchTerm)     
                var propertyQuery = (from property in filterProperties
                                     let toStringMethod = Expression.Call(
                                                         Expression.Call(Expression.Property(paramExpression, property), convertToString, null),
                                                             typeof(string).GetMethod("ToLower", new Type[0]))
                                     select Expression.Call(toStringMethod, typeof(string).GetMethod("Contains"), searchExpression)).ToArray();

                for (int j = 0; j < propertyQuery.Length; j++)
                {
                    //  Nothing to "or" to yet
                    if (j == 0)
                    {
                        compoundOrExpression = propertyQuery[0];
                    }

                    compoundOrExpression = Expression.Or(compoundOrExpression, propertyQuery[j]);
                }

                //  First time around there is no And, only first set of or's
                if (i == 0)
                {
                    compoundAndExpression = compoundOrExpression;
                }
                else
                {
                    compoundAndExpression = Expression.And(compoundAndExpression, compoundOrExpression);
                }
            }

            //  Create expression
            return Expression.Lambda<Func<T, bool>>(compoundAndExpression, paramExpression);
        }

So to clarify, I basically want the user to be able to type a single string in a textbox, and then show any rows that have a field that contains that string. My handler is generic so it needs to use reflection to get to the properties.





Copying a discriminated union object

I want to make a copy of an object that is of a discriminated union type, with one or two particular fields assigned different values and any other fields copied straight across.

The tricky part is that I'm trying to write a function to do this, that will keep working unchanged even as more cases are added to the union, so I can't use match; instead, I'm looking for a solution that uses reflection to examine the fields of the particular case. Here's what I have so far on the reverse side, extracting values from an object regardless of its exact type:

let case a =
    match FSharpValue.GetUnionFields (a, typeof<Term>) with
    | info, _ ->
        info

let unpack a =
    let fields = List.ofSeq ((case a).GetFields ())
    List.collect
        (fun (field: PropertyInfo) ->
            let t = field.PropertyType
            if t = typeof<Term> then
                [field.GetValue a :?> Term]
            elif t.IsGenericType && t.GenericTypeArguments.[0] = typeof<Term> then
                field.GetValue a :?> Term list
            else
               []
        )
        fields

And I'm trying to write a function that starts off something like:

let pack a xs =
    let fields = List.ofSeq ((case a).GetFields ())
    ...

It occurred to me to try to use MemberwiseClone but that's protected, so can't be used outside subclasses. I'm probably looking for something like 'create a new object of this type, then step through the fields copying across or filling in values as appropriate' though I'm not quite sure what 'this type' would be, since GetType doesn't work on discriminated unions. What's the best way to go about it?





How to access anonymous method from generic list?

I've been working on a library to generate fake data using Faker.NET. The problem I'm having is that I don't know how to access an anonymous method that I'm passing to the constructor of my DataGenerator child classes.

The issue is that in order to create a list of generics I had to create base class DataGenerator but I cannot pull my Func<T> member up because that base class is not generic so no Tavailable. However, my DataGenerator<T> class does expose the Generator property which is my anonymous method but I haven't found a way to access it while iterating my list of data generators.

Any advice will be highly appreciated.

This is what I have so far:

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Guid EmpUid { get; set; }
}

// Define other methods and classes here
public abstract class DataGenerator
{
    public abstract int GetWeight(string matchingProperty);
    public abstract Type Type { get;}
}

public abstract class DataGenerator<T> : DataGenerator
{
    public readonly string[] Tags;
    public readonly Func<T> Generator; 
    protected DataGenerator(Func<T> generator, params string[] tags)
    {
        Tags = tags;
        //How to access this?
        Generator = generator;
    }

    public override int GetWeight(string matchingProperty)
    {
        int sum = (from tag in Tags
            where matchingProperty.ToLowerInvariant().Contains(tag.ToLowerInvariant())
            select 1).Sum();
        return sum;
    }

    public override Type Type {
        get { return typeof(T); }
    }
}

public class StringDataGenerator : DataGenerator<string>
{
    public StringDataGenerator(Func<string> generator, params string[] tags) : base(generator, tags)
    {
    }
}

public class GuidDataGenerator : DataGenerator<Guid>
{
    public GuidDataGenerator(Func<Guid> generator, params string[] tags)
        : base(generator, tags)
    {
    }
}

And I'm testing it here:

private static void Main(string[] args)
    {
        var dataGeneratorList = new List<DataGenerator>
        {
            new StringDataGenerator(Name.First, "first", "name"),
            new StringDataGenerator(Name.Last, "last", "name"),
            new GuidDataGenerator(Guid.NewGuid, "uid", "id")
        };

        var writeProperties = typeof (Employee).GetProperties().Where(p => p.CanWrite);
        foreach (var property in writeProperties)
        {
            foreach (var dataGenerator in dataGeneratorList)
            {
                if (property.PropertyType == dataGenerator.Type)
                {
                    var weigth = dataGenerator.GetWeight(property.Name);
                    //How to access generator here???
                    var testValue = dataGenerator.Generator.Invoke();
                }
            }
        }
    }





Access path variable in FileInputStream using reflection

I came across some code that uses reflection to get to the "path" variable in the FileInputStream!! Weirder part is that commons.lang.reflect.FieldUtils.readField(is, "path", true) throws a java.lang.IllegalArgumentException. That too intermittently... May be some specific scenario leads to that, but I am not able to figure out. Any pointers as to what could cause reflection to fail to "see" the Field?

The code is buried in lot of Cascading workflows related mumbo jumbo but here is the relevant part -

//This same method is invoked multiple times on same file. If it matters?
    method(SourceCall<Object, InputStream> sc) {
        InputStream is = sc.getInput();
        if (is instanceof FileInputStream) {
             FileInputStream fileInputStream = (FileInputStream)is;
             //The line below throws IllegalArgumentException - sometimes
             String fileName = (String)FieldUtils.readField(fileInputStream , "path", true);
             return fileName;
         }
    }





Generic scala trait

I need to write a generic trait, which can return the class of its generic type. Here is what I am trying to implement, but I can't get it to compile:

trait MyTrait[T] {
  implicit def classTagT: ClassTag[T]

  def foo(t: T): Unit
  def getType(): Class[T] = classTagT.runtimeClass
}

What is the best way to accomplish this? Should I be writing a macro instead?





C# Expression Call, Can't seem to get the method info and parameters correct

Here is the error:

An exception of type 'System.ArgumentException' occurred in... Additional information: Expression of type 'System.Func`2[Business.Entities.SlateEmployee,System.Boolean]' cannot be used for return type 'System.Boolean'

Can anyone see what is wrong with my code.

 public class ClearValueAction : ActionRuleBase
{
    /// <summary>
    /// Virtual method to call during actions
    /// </summary>
    /// <returns></returns>
    public override bool ExecuteAction<T>(T dataObject)
    {
        PropertyInfo propertyInfo = typeof (T).GetProperty(Left);
        if (propertyInfo != null)
        {
            ReflectionUtils.SetObjectValue(dataObject, null, propertyInfo);
            return true;
        }
        return false;
    }

    /// <summary>
    /// Making an expression to call the ExecuteAction function when this is compiled
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public override Func<T, bool> CompileRule<T>()
    {

        //return Expression.Lambda<Func<T, bool>>().Compile();
            ParameterExpression allParameters;
            var methodCall = CreateLambda<T>("ExecuteAction", "dataObject", out allParameters);


//ERROR IS HERE//////////////////////////////////////////////
            var lambda = Expression.Lambda <Func<T, bool>>(methodCall, allParameters);
        return lambda.Compile();

    }

    private LambdaExpression CreateLambda<T>(string methodName, string methodInputParamName, out ParameterExpression allParameters)
    {

        allParameters = Expression.Parameter(typeof(T), methodInputParamName);
        var c = Expression.Constant(methodInputParamName);
        MethodInfo methodInfo = typeof(ClearValueAction).GetMethods().First(m => m.Name == methodName && m.IsGenericMethod).MakeGenericMethod(typeof(T));
        MethodCallExpression generateCallExpression = GenerateCallExpression(this, methodInfo, allParameters);
        return Expression.Lambda(generateCallExpression, allParameters);
    }

    /// <summary>
    /// Generate expression call
    /// </summary>
    /// <param name="instance">If instance is NULL, then it method will be treated as static method</param>
    private static MethodCallExpression GenerateCallExpression(object instance, MethodBase method, ParameterExpression allParameters)
    {
        var methodInfo = method as MethodInfo;
        // it's non static method
        if (instance != null)
        {
            var instanceExpr = Expression.Convert(Expression.Constant(instance), instance.GetType());
            return Expression.Call(instanceExpr, methodInfo, allParameters);
        }

        // it's static method
        return Expression.Call(methodInfo, allParameters);
    }

    private static List<Expression> GenerateParameters(MethodBase method, out ParameterExpression allParameters)
    {
        allParameters = Expression.Parameter(typeof(object[]), "params");
        ParameterInfo[] methodMarameters = method.GetParameters();
        List<Expression> parameters = new List<Expression>();
        for (int i = 0; i < methodMarameters.Length; i++)
        {
            var indexExpr = Expression.Constant(i);
            var item = Expression.ArrayIndex(allParameters, indexExpr);
            var converted = Expression.Convert(item, methodMarameters[i].ParameterType);
            parameters.Add(converted);
        }

        return parameters;
    }

}





How can I get the ReturnType of an anonymous method passed as a parameter through reflection?

Let's say I have a simple class like this:

public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public readonly Func<object> GuidGen;

public Employee(Func<object> guidGen)
{
    GuidGen = guidGen;
    var methodInfo = GuidGen.GetMethodInfo();
    var returnType = methodInfo.ReturnType;
    //ReturnType returns System.Object! not Guid
}
}

When creating an instance I pass an anonymous method that returns a Guid:

    var emp = new Employee(() => 
    {
        return Guid.NewGuid();
    }
    );
    var guid = emp.GuidGen.Invoke();

My question is, is it possible to get the ReturnType for the anonymous method I'm passing through the Employee constructor? When I debug I get a ReturnTypeof System.Object instead of Guid type.





I am looking for a way to loop a DataSet to fill a set List the data in the the DataSet could be in multiple DataTables in the DataSet. I have a object that has the list of column names that are needed. If I loop the object to the Dataset it will not work.

public List<Customer> BuildCustomerList(DataSet ds, Customer oCustomer)
{
    List<Customer> lCustomers = new List<Customer>();
    foreach (PropertyInfo p in typeof(Customer).GetProperties())
    {
        Customer oC = new Customer();
        foreach(DataRow dr in ds.Tables[0].Rows)
        { 
            foreach(DataColumn dc in ds.Tables[0].Columns)
            {
                if(p.Name == dc.ColumnName)
                {
                    p.SetValue(oC, dr[dc].ToString());
                }
            }  
        }
        lCustomers.Add(oC);
    }
    return lCustomers;
}

I did look at How to Convert DataTable to List using Reflections This will work if I am using a DataTable but I am not sure how to make it work with a DataSet which has multiple DataTables.





Match Object with Dataset.Datatable.Column and loop the data inside [duplicate]

This question already has an answer here:

I made a matching system where a user could upload .CSV files and match the data with our data objects. I have the matching system down, what I need help with is getting the data out of the files and matching them to the objects. I am saving the files to a DataSet one file per DataTable, at first I thought I would loop the objects and the DataSet to add the data.

public List<Customer> BuildCustomerList(DataSet ds, Customer oCustomer)
    {
        List<Customer> lCustomers = new List<Customer>();
        foreach (PropertyInfo p in typeof(Customer).GetProperties())
        {
            Customer oC = new Customer();
            foreach(DataRow dr in ds.Tables[0].Rows)
            { 
                foreach(DataColumn dc in ds.Tables[0].Columns)
                {
                    if(p.Name == dc.ColumnName)
                    {
                        p.SetValue(oC, dr[dc].ToString());
                    }
                }  
            }
            lCustomers.Add(oC);
        }
        return lCustomers;
    }

But this will not work, and if I start with loping the DataSet first it will also not work. I am looking for a solution to loop the Data and save them to a list of objects.





IndexOutOfRangeException when trying to access the generic arguments of a Func

I need to get the generic argument type from a factory delegate (Func<object), but it always results in a IndexOutOfRangeException.

public void Bind(Type service, Func<object> factory) {
    var factoryResultType = factory.Method.GetGenericArguments()[0]; // ex
}

// extension
public static void Bind<TService>(this IBinder binder, Func<TService> factory)
    where TService : class 
{
    binder.Bind(typeof(TService), (Func<object>) factory);
}

// usage
var dummyClass = new DummyClass();
binder.Bind<IDummy>(() => dummyClass);





lundi 27 avril 2015

Class.getConstructor fails to find compatible constructor

Having problems with a factory class, I pass in a human readable name that maps to a class that has a single constructor with a single argument, I get the following error:

java.lang.NoSuchMethodException: com.satgraf.evolution2.observers.VSIDSTemporalLocalityEvolutionObserver.<init>(com.satlib.evolution.ConcreteEvolutionGraph)
at java.lang.Class.getConstructor0(Class.java:2892)
at java.lang.Class.getConstructor(Class.java:1723)
at com.satlib.evolution.observers.EvolutionObserverFactory.getByName(EvolutionObserverFactory.java:84)
at com.satgraf.evolution2.UI.Evolution2GraphFrame.main(Evolution2GraphFrame.java:229) 

These are the classes in question, I have about a dozen of these things in different projects, they all work without problem - including one that is almost identical, can't see why this one is failing:

public EvolutionObserver getByName(String name, EvolutionGraph graph){
if(classes.get(name) == null){
  return null;
}
else{
  try {
    Constructor<? extends EvolutionObserver> con = classes.get(name).getConstructor(graph.getClass());
    EvolutionObserver i = con.newInstance(graph);
    observers.add(i);
    return i;
  } 
  catch (InvocationTargetException | InstantiationException | IllegalAccessException | NoSuchMethodException | IllegalArgumentException | SecurityException ex) {
    Logger.getLogger(EvolutionObserverFactory.class.getName()).log(Level.SEVERE, null, ex);
    return null;
  }
}
}

The class being instantiated is:

public class VSIDSTemporalLocalityEvolutionObserver extends JPanel implements EvolutionObserver{
    public VSIDSTemporalLocalityEvolutionObserver(EvolutionGraph graph){
    ...
    }
...
}

The argument graph is of type:

public class ConcreteEvolutionGraph extends ConcreteCommunityGraph implements EvolutionGraph{
    ...
}





Using MethodHandle reflection with JDK 6?

Strange situation here. I need to invoke the same class instance method many many times (1000/second range) without the ability to import or build against the library needed. I am trying to call a method within my JEE project that uses a class from an application server's provided library. The JEE project still needs to run on other application servers so I cannot simply build against that library. Reflection is the only solution I think.

When going so rapidly, time to execute is orders of magnitude slower using reflection than with direct invocation.

After some research, I discovered static final MethodHandlers:

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;



public class Test {

    static final MethodHandle sfmh;

    static {
        MethodHandle mh = null;
        try {
            final Class<?> clazz = Class.forName("com.me.lib");
            Method m = clazz.getMethod("MyMethod");
            mh = MethodHandles.lookup().unreflect(m);
        } catch (Throwable e) {
            mh = null;
        }

        sfmh = mh;
    }

    public static void main(String[] args) throws Throwable {
        int i = 0;
        System.out.println("starting");
        long start = System.currentTimeMillis();
        for(i = 0; i < 1000000000; i++) {
            sfmh.invokeExact();
        }
        long total = System.currentTimeMillis() - start;
        System.out.println("Time: " + total + " milliseconds");
    }

}

The works great and gets me an acceptable speed result (2-4 times slower instead of 200x slower). There seems to be an issue to this perfect solution -- I need this to run on Java 6 (boo, hiss, it's a requirement)

When compiling against 1.6 I get:

Invocation of polymorphic methods not allowed for source level below 1.7

on the line

sfmh.invokeExact();

Are there any acceptable solution that takes advantage of the concept of MethodHandle that works with 1.6?





How do you call GetMethod for a generic function that takes a generic parameter?

I know I can fetch the method info using GetMethods, but I want to know how to do it properly without GetMethods. I have read other SO questions and answers that suggest this is not possible, or suggest just using LINQ instead, but that isn't really an answer to the question.

Consider at the most basic level, a static generic function that takes a single generic parameter.

private static void Test<T>(T val)
{
}

To fetch this method info we can just call Type.GetMethod("Test", BindingFlags.Static | BindingFlags.NonPublic). However if there were some reason we could not use this simple GetMethod signature (perhaps due to multiple overloads), then we need to supply the parameter types. The problem is that I cannot create a parameter type that accurately matches the T val parameter. What's interesting is that I can take the parameters from the method info (fetched with GetMethods) and pass that into GetMethod to get the desired outcome. This means that if it were only possible to create the appropriate generic types (with IsGenericParameter set to true) then I feel like this would be completely possible.

So that means that this is entirely possible in .NET, and only require the creation of the proper type instances. How does one create these type instances? And if they are not possible to create, why aren't they?

I created a simple fiddle to showcase the issue.





Using GetType/instanceof in C# vs. alternatives

I've come across a problem in a game I am making in C#. It's a simple tile based matching game, and the problem has come up for a power up I am trying to make:

Say we have basic tile types, circles squares and diamonds, which are all subclasses of Tile. Instead of having circles only match to circles, I tried to extract the "matches" behavior to an abstract Tile method: canMatchWith(Tile t). The Tiles also have two methods to add/remove Tiles they can match with.

So say we have a Circle tile in the middle of our game, and we have a powerup that says "Circle tiles can match with square tiles this turn". I would go through all of the Circle tiles and say circleTile.addCanMatchWith(typeof(Square)). Internally, we have a List canMatchWith.

Then later, I want to say "Circles can no longer match with squares" and simply say circleTile.removeCanMatchWith(typeOf(Square)).

This is my current solution, and it works great with no performance drawbacks that I've noticed (It's a tile based matching game, so these types are only evaluated once per 'move', not frame by frame). However, the voice in my head is telling me that this is a bad way to accomplish this behavior. So I have some alternatives:

  1. Enums... Each Tile could be composed with a Tiletype type variable. This would be initialized in the constructor and set to Type.SQUARE for squares, and so on. Then, each Tile would have a List canMatchWith, and the functionality is the same as my original implementation. Except in this case, it's a little trickier. Say I have some circle subclasses, oval and elipse. I want ovals to be able to match with ONLY squares, but elipses can match with all circles and not squares.

The problem here is redundancy, my enum would now have OVAL and ELIPSE as well, and the Elipse class would have (CIRCLE, OVAL, ELIPSE TileTypes) as types it can match with. This is completely redundant, I want to just say "Circle" which I could with the types. I suppose the Tiles could have TileType baseType and TileType actualType.

  1. Some form of behavior composition. Forget Tile subclasses, just give Tiles methods and an instance variable for List. Then, at runtime we can just say someTile.addCanMatch(new CircleMatchBehavior()). This seems silly, as I would have a bunch of classes just saying you can match with a particular shape.

In summary, what I am trying to accomplish is having multiple object types be able to interact with any number of different types. The question is, what should I be using for the Type. Is it okay to use GetType here? Enums? Or is there a better strategy someone would recommend? I'm trying to be as general as possible, these tiles should not have any hardcoded dependencies on other tiles, and must be able to change who they can interact with on the fly. Say I make a new Tile subclass, pentagon... well, Pentagons can match with Squares, Circles, and Pentagons. Easy with my implementation, but something is telling me this is a dirty OOP practice.

I feel like I have to use Types/Enums because I am not trying to say thisTile.addCanMatch(Tile someOtherObject). That is too specific, I want thisTile to be able to match with all tiles who are instances of a particular class.





C# method tagging

I'm creating a database application in C# and so I wrote a Query class. I want to mark a method inside the class as a step of the query's initialization so I could dynamically build different types of queries using only one class. I noticed there is an AttributeUsage tag but I'm not familiar it. My question is how can I create my own tag, or how can I use an existing attribute for my own need? This is my direction:

[InitializationStep]
SetArguments(object[] args)
{
    // some code
}
[InitializationStep]
SetDatabaseName(object[] args)
{
    // some code
}
...

I also need a way to tell my classes that one method is an overloaded version of another. Thanks very much.





Issues reading properties.config file using reflection

I have a static class and I write it's values into "properties.config" using reflection. This is done when I close my application. The static class values change during the program. I`m having trouble reading from the "properties.config" back to my static class during start up.

Any help is greatly appreciated.

field.set(null, prop.getProperty(field.getName()));

The object value is null, because it is a static class. But the program is erroring out here.

Write Method :

private void writeProperty() {
    Properties prop = new Properties();
    OutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream("resources/config.properties");
        Field[] fields = PropertyCl.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                prop.setProperty(field.getName(), field.get(null).toString());
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        prop.store(outputStream, "Config for UI");
    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Read Method : [Issues here]

/**
 * Reading from config.properties and setting fields in the static class
 */
private void readProperties() {
    Properties prop = new Properties();
    InputStream inputStream = null;

    try {
        inputStream = new FileInputStream("resources/config.properties");
        prop.load(inputStream);

        Field[] fields = PropertyCl.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                try {
                    field.set(null, prop.getProperty(field.getName()));
                    //System.out.println("Check >> " + field.get(field) + " ::: " + prop.getProperty(field.getName()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}





How to modify or substitute private method in a java class

I have a class which behavior I would like to change. I need to replace private method with another realization. Common reflection techniques allow to modify private variable or to invoke private methods. But I find little information about replacing entire methods.

I presume that there are advanced techniques to do so. May be its impossible with standard java reflection but there are probably other tools to recompile byte code in runtime.





Get other properties attributes while validating a custom attribute

I have created a validation attribute. And the IsValid method is as follows

<AttributeUsage(AttributeTargets.Field Or AttributeTargets.Property, AllowMultiple:=True)> _
Public NotInheritable Class BlaBlaAttribute
        Inherits ValidationAttribute

        Private ReadOnly _typeId As New Object()
        ...........

        Protected Overrides Function IsValid(value As Object, validationContext As ValidationContext) As ValidationResult

               Dim otherProperties = validationContext.ObjectType.GetProperties(BindingFlags.IgnoreCase Or BindingFlags.Public Or BindingFlags.Instance).ToList()

               For Each item In otherProperties
                    Dim propItem = item
                    Dim attr As DisplayNameAttribute = DirectCast(Attribute.GetCustomAttribute(propItem, GetType(DisplayNameAttribute)), DisplayNameAttribute)
                    If attr Is Nothing Then
                    ............
                    End If
               Next
               Return ValidationResult.Success
        End Function
End Class

Thought, there are some display attributes but "attr" is always nothing. How to get other properties custom attributes? Any help would be highly appriciated





getField java reflection

i have a generic method in java to get fields value by reflection.

private static Object getFieldValue(Object object, final String fieldName) {

if (null == object) {
  return null;
}

Class<?> clazz = object.getClass();
while (clazz != null) {
  try {
    Field field = clazz.getDeclaredField(fieldName);
    field.setAccessible(true);
    try {
      return field.get(object);
    } catch (IllegalArgumentException e) {

      e.printStackTrace();
    } catch (IllegalAccessException e) {

      e.printStackTrace();
    }            
  } catch (NoSuchFieldException e) {
    clazz = clazz.getSuperclass();
  } 
}
return null;  

}

it works fine for simple fields name, exemple getfieldValue (project, "title"), i want to get fields values of related objects for exemple

getfieldValue (project, "task.title")





C#: How to extend PropertyInfo?

I have a solution where i get to map out all properties and sub-properties of an object into a Dictionary. Lets say I have something like these objects:

class MyClassA{
    string info;
}
class MyClassB{
    string info;
}
class MyClassC{
    MyClassA a;
    MyClassB b;
    string something;
}
class MyClassD{
    MyClassC c;
}

I created an utility to map out all the propreties so i can get something like:

MyClassD dObject = Something();
Dictionary<string, PropertyInfo> propertyMap = new Dictionary<string, PropertyInfo>();

propertyMap = buildPropertyMap(dObject );

where the string is the path and the PropertyInfo the actual property. The strings on the Map on this example would look like this (pseudo-output):

propertyMap.Keys={
    c;
    c.a;
    c.b;
    c.a.info;
    c.b.info;
    c.something;
}

This is a great way to tell what goes where when reading for example data from an excel file and not from xml-like things, like so:

ExcelTableC:

 -----------------------
1|Ainfo|Binfo|Csomething|
-------------------------
2|value|value|valuevalue|
3|value|value|valuevalue|
 -----------------------

It wall works great. Now thing is, this is all obviously inside a couple of loops and diferent functions (because of the Excel reading process) and i need later to get the key, this is, lets say I have this 'property' and I want the path (dont ask why):

// this method does not exist (pseudo-code)
PropertyInfo.GetPath; //it would return 'c.b.info' for ex. or 'c.a.info'

So i wanted to implement a class that extended PropertyInfo to add my methods.

But doing something like:

public class PropertyField : PropertyInfo
{
    PropertyField parent;
    string path;
    // etc...
}

returns error because PropertyInfo is an abstract class and I would need to implement all inhereted members.

I can add 'abstract' to 'PropertyField' like this:

public abstract class PropertyField : PropertyInfo {}

But then when i try to cast it like this :

private void findProperties(Type objType)
{
    PropertyInfo[] properties = objType.GetProperties();

    for (int i=0; i< properties.Length; i++)
    {
        //PropertyInfo propertyInfo = properties[i];
        PropertyField property = (PropertyField) properties[i];
        //do something with it
    }
}

will return the following error:

System.InvalidCastException: Unable to cast object of type 
'System.Reflection.RuntimePropertyInfo' to type 'App.models.PropertyField'.

So the question is, how do I add these methods? If I cant inherit what can i do?





dimanche 26 avril 2015

three js mirror not reflecting all meshes

Objective:

  • To simulate a reflective floor in three js.

Idea:

  • Make the floor translucent by setting opacity to 0.5.
  • Place a Mirror below it to reflect the meshes above it.

Expected Output:

  • To be able to see reflections of the house via the floor mirror.

Obtained Output:

  • Doesn't reflect the meshes which is part of the house.
  • Instead, reflects only the skybox and that too only in certain angles.

Screenshots:

Questions:

  • Why aren't the other meshes of the house reflected through the mirror?
  • Why is the mirror not reflecting in certain orientations of the camera?

Code Attached:

.......
.......
function getReflectiveFloorMesh(floorMesh) {

        var WIDTH = window.innerWidth;
        var HEIGHT = window.innerHeight;

        floorMirror = new THREE.Mirror( renderer, firstPerson.camera,
                    { clipBias: 0.003,
                    textureWidth: WIDTH,
                    textureHeight: HEIGHT,
                    color: 0x889999 } );

        var mirrorMesh = floorMesh.clone();

        mirrorMesh.position.y -= 10;            // Placing the mirror just below the actual translucent floor; Fixme: To be tuned
        mirrorMesh.material = floorMirror.material;

        mirrorMesh.material.side = THREE.BackSide;  // Fixme: Normals were flipped. How to decide on normals?
        mirrorMesh.material.needsUpdate = true;

        mirrorMesh.add(floorMirror);

        return mirrorMesh;

    }

    function getSkybox() {
        var urlPrefix = "/img/skybox/sunset/";
        var urls = [urlPrefix + "px.png", urlPrefix + "nx.png",
            urlPrefix + "py.png", urlPrefix + "ny.png",
            urlPrefix + "pz.png", urlPrefix + "nz.png"];
        var textureCube = THREE.ImageUtils.loadTextureCube(urls);

        // init the cube shadder
        var shader = THREE.ShaderLib["cube"];
        shader.uniforms["tCube"].value = textureCube;
        var material = new THREE.ShaderMaterial({
            fragmentShader: shader.fragmentShader,
            vertexShader: shader.vertexShader,
            uniforms: shader.uniforms,
            side: THREE.BackSide
        });

        // build the skybox Mesh
        var skyboxMesh = new THREE.Mesh(new THREE.CubeGeometry(10000, 10000, 10000, 1, 1, 1, null, true), material);

        return skyboxMesh;
    }

    function setupScene(model, floor) {
        scene.add(model); // Adding the house which contains translucent floor
        scene.add(getSkybox()); // Adding Skybox
        scene.add(getReflectiveFloorMesh(floor)); // Adds mirror just below floor

        scope.animate();
    }
....
....
this.animate = function () {

    // Render the mirrors
    if(floorMirror)
        floorMirror.render();

    renderer.render(scene, firstPerson.camera);
};





How would I get the name of the parameters in a function

I have a function

void print(stack<T>& One, stack<T>& Two, stack<T>& Three);

and I would like to output the parameter names (i.e. cout << "One")

How would I go about doing that?





How to get default constructor parameter using reflection?

This kind of seemed easy to figure out but now am confused:

scala> class B(i:Int)
defined class B

scala> classOf[B].getDeclaredFields
res12: Array[java.lang.reflect.Field] = Array()

Note this:

scala> class C(i:Int){
     | val j = 3
     | val k = -1
     | }
defined class C

scala> classOf[C].getDeclaredFields
res15: Array[java.lang.reflect.Field] = Array(private final int C.j, private final int C.k)





c# Reflection create instance of interface with generic

Is it possible via reflection to create an instance of an interface that has a generic, with both the generic and object type dynamically set?

public interface IRead<T>
{
    IList<T> Map();
}

public class FooRead : IRead<Bar>
{
    public IList<Bar> MapFile()
    {
        return new List<Bar>();
    }
}

So I want to set Foo and Bar dynamically at run time, and if possible keep the object strongly typed.

Ive got the interface type with its generic working, but cant figure out how to assign the dynamic object type

    var barType = Type.GetType("Bar");
    var reader = typeof(IRead<>);
    Type[] typeArgs = {barType}
    var readerInit = reader.MakeGenericType(typeArgs)

Additionally I got the interface set to a dynamic object

   var fooType = Type.GetType("FooRead");
   var reader = (IRead<Bar>)Activator.CreateInstance(fooType);

Havent figured out how to get both of these pieces together..





Bad practice to set private/protected methods to "public" during runtime

Okay I don't know if it's bad design but I feel a bit bad about doing the following:

abstract class A
{
    abstract public function getCallable(); 
}

class B extends A
{
    public function getCallable()
    {
        return array($this, 'doSomething');
    }

    protected function doSomething()
    {
        // Do stuff here
    }
}

The reason why B::doSomething is protected is that I don't like to expose this method because it should only be called from somewhere else in the code where I do a call_user_func() for the return value of B::getCallable.

You should be free to organize yourself in the subclasses of A. Without exposing anything to the outside. So the "API" won't change to the view outside of the subclasses of A.

So you should not be able to do something like:

$b = new B();
$b->doSomething();

the only way to get B::doSomething executed should be over:

$b = new B();
call_user_func($b->getCallable());

So I'm thinking about how I could achieve that. One way I could think of is create a ReflectionMethod object from B::getCallable()'s return value and set it to accessable if the method is not public.

I don't like this solution also it would work but is not that elegant:

class B extends A
{
    public function getCallable()
    {
        return function()
        {
            $this->doSomething();
        };
    }

    protected function doSomething()
    {
        // Do stuff here
    }
}

Any good suggestions or other ideas how to work around this?





How to call a simple getter method in Groovy?

I can't believe I have to ask this question, it's really confusing. The goal of this question is to figure out why and/or find an easier way (than reflection) to get the correct result.

Back story

I loaded some class files from directories and jar files via a URLClassLoader and I'd like to dump all the class names and their declared methods. The classes cannot be initialized (see false) because if any code runs in those classes exceptions may be thrown due to some missing dependencies. I ran into this problem while trying to output just the class names.

Question

What am I missing, how can I work around Groovy's magic and just simply call a method (called getName) on an object (of type java.lang.Class) without reflection? Someone also please point to the specification as to why this work this way.
Here's the output for my mini-test (see below) and my comments:

.name // magically initializes class X and calls X.get("name")
name and Y

.getName() // tries to reload class Y in another ClassLoader and initialize it
X and NO INITIALIZATION

["name"] // this is just plain magic! What a Terrible Failure :)
name and NO INITIALIZATION

reflection // obviously works, becase it's really explicit
X and Y

Test harness and test-cases

Changing the test closures to be explicit on the argument type (Class<?> c -> makes no difference.

new File("X.java").write('''
    public class X {
        public static String get(String key) {
            return key;
        }
    }
    ''');
new File("Y.java").write('''
    public class Y {
        static {
            if (true) // needed to prevent compile error
                throw new UnsupportedOperationException("NO INITIALIZATION");
        }
    }
    ''');
print 'javac X.java Y.java'.execute().err.text;


def test = { String title, Closure nameOf ->
    URL url = new File(".").toURI().toURL();
    // need a new ClassLoader each time because it remembers
    // if a class has already thrown ExceptionInInitializerError
    ClassLoader loader = java.net.URLClassLoader.newInstance(url);
    // false means not to initialize the class.
    // To get the name of the class there's no need to init
    // as shown in the reflection test.
    // Even fields and methds can be read without initializing,
    // it's essentially just parsing the .class file.
    Class x = Class.forName("X", false, loader);
    Class y = Class.forName("Y", false, loader);

    println()
    println title
    try {
        print nameOf(x)
    } catch (Throwable ex) {
        print ex.cause?.message
    }
    print " and "
    try {
        print nameOf(y)
    } catch (Throwable ex) {
        print ex.cause?.message
    }
    println()
}

test '.name', { c -> c.name; }
test '.getName()', { c -> c.getName(); }
test '["name"]', { c -> c["name"] }
test 'reflection', { c -> java.lang.Class.class.getDeclaredMethod("getName").invoke(c); }





samedi 25 avril 2015

C# How to use reflection to cast a control as its type in order to modify properties?

Here's an example of what I currently do:

book enable = false;
foreach (Control c in controlList)
        {
            if (c is MyTextBox)
            {
                (c as MyTextBox).Enabled = enable;
            }
            if...
            ...
        }

Instead of having multiple if statements for every type of control, is there a way to get the type of the control in order to cast and then be able to access and set a property of that control?





how do you log function call return values in golang

I want to know the return values at time of exit from a golang function. The golang defer mechanism is helpful, but it evaluates arguments at the time the defer statement is registered rather than when it is executed. I can work with this using an anonymous function which accesses the return values:

func try() (int i) {
  defer func() {fmt.Printf("%d", i)}()
  i = 10
  return i+1
}

func main() {
  try()
}

This would work ok, i think, but I would like to handle this in a generic manner, perhaps something like:

func try(in string) (out int) {
  enter("%s", in);exit("%d", out)
}

or, even better, use reflection to output the arguments/return values at time of entry/exit. I'm assuming runtime performance isn't critical :).

Is there a good way to do this? Shaba Abhiram's handy Tracey lib does go a long way towards this but stops short of printing the return values.





C# VS doesn't handle exception in constructor when using reflection [duplicate]

This question already has an answer here:

Assuming this class:

public class Smurf
    {
        public Smurf()
        {
            throw new Exception("Smurfs do not exist");
        }
    }

When trying to create an instance like this, it works as expected:

    try
    {
        var smurf = new Smurf();
    }
    catch (Exception)
    {

    }

However when using reflection VS incorrectly tells me that my exception is unhandled.

    try
    {       
        var smurf = (Smurf)Activator.CreateInstance(typeof(Smurf));
    }
    catch (Exception)
    {

    }

I've spent hours trying to find the initial problem when I finally came up with this as I was sure I was handling the exception correctly. I believe there are some settings (not quite sure though) in VS which I could use to stop this from happening, but I don't really want to thing about that since the code is deployed for other users and they would have to do the same.

Is there any other way or solution to this?





vendredi 24 avril 2015

The non-generic type 'System.Collections.ArrayList' cannot be used with type arguments

I read a private field via reflection:

var parameters = typeof(HqlProvider).GetField("paramList", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(query);

And it works fine. I can put in a breakpoint and see everything. But when I try to cast parameters to what it is (an ArrayList) I get The non-generic type 'System.Collections.ArrayList' cannot be used with type arguments.

How can it not cast it to the thing that it is?





Cannot get attribute from PropertyInfo c#

I have a class and interface set up like this:

public partial interface INav_Item 
{
        [FieldID("df918977-369c-4a06-ac38-adb8741b5f75")]
        string Title  {get; set;}
}


public partial class Nav_Item  : INav_Item 
{
        [FieldID("df918977-369c-4a06-ac38-adb8741b5f75")]
        public virtual string Title  {get; set;}
}

And then I have this class inherited:

public class MenuItem : Nav_Item
{
        public virtual IEnumerable<MenuItem> Children { get; set; }

        //some other properties
}

I'm now trying to instantiate an object of type MenuItem, and trying to get the attributes from the Inherited class (I can't instantiate MenuItem directly, because the type is being passed in from other classes)

object obj = Activator.CreateInstance(type);

foreach (PropertyInfo propInfo in type.GetProperties())
{
            FieldAttribute sfi =(FieldAttribute)propInfo.PropertyType.GetCustomAttribute(typeof(FieldAttribute));

}

But this is giving me sfi to be null. I've also debugged to try getting all the attributes:

propInfo.PropertyType.GetCustomAttributes()

.. but this is only giving me the system attributes (type and something else), but my own attributes are just not there? Is this is because the class is inherited? How can I get the attribute value?

EDIT:

The attribute class is defined as this:

public class FieldIDAttribute : Attribute
{
    private string _id;

    public FieldAttribute(string Id)
    {
        _id = Id;
    }

    public ID TheFieldID
    {
        get
        {
            return new ID(_id);
        }
    }
}





Get Object type from PropertyType?

I have Type of a property. propertyType is basically a

public abstract Type PropertyType { get; }

From this I want to know Object type which is Employee:

propertyType    {Name = "Employee[]"  FullName = "DataContract.Employee[]"}

How can I get this?





How to run with system permission

My app is trying to get system VPN profiles list with hidden APIs. However, the hidden APIs need to run in system process. After google, I find this, which can create a new process with root permission.

  Process suProcess = Runtime.getRuntime().exec("su");

But it can only run shell commands in the new process. How can I run my custom function in the new process?





jeudi 23 avril 2015

interface Borrowable {
  Date getCheckoutDate();
  Date getDudeDate();
  void setCheckoutDate(Date d);
  void setDudeDate(Date d);
}

next class has all the functions that an arraylist has. I have tested all of them and they work perfectly.

class LibraryCollection<E> {
  ArrayList<E> items = new ArrayList<>();

  public Iterator<E> iterator() {return items.iterator();}
  boolean add(E o) {return items.add(o);}
  boolean addAll(Collection<? extends E> c) {...}
...
.....
......
}

here is where I cannot figure up how to make " T[] getOverDueBooks(Date date)" to return a valid array

class ChechOutCart<E extends Borrowable> extends LibraryCollection<E> {
  ArrayList<E> dueOnSpecificDate = new ArrayList<>();
  ArrayList<E> dueOn = new ArrayList<>();

  <T> T[] getOverDueBooks(Date date) {
    T[] a = (T[]) java.lang.reflect.Array.newInstance(items.getClass().getComponentType(), items.size());
    Borrowable current;
    DVD d;
    Book b;

    for (int i = 0; i < items.size(); i++) {
      current = this.items.get(i);

      if (current instanceof Book) {
        b = (Book) current;
        if (date.after(b.getDudeDate())) {
          dueOn.add(this.items.get(i));
        }
      } else if (current instanceof DVD) {
        d = (DVD) current;
        if (date.after(d.getDudeDate())) {
          dueOn.add(this.items.get(i));
        }
      }
    } 
    return dueOn.toArray(a);
  }
}

in main I have made a cauple of DVD and Book objects and they are fully initialized I have omitted the initialization cause too long. I have put then in myCar

public static void main(String[] args) {
    ChechOutCart<Borrowable> myCar = new ChechOutCart<>();
    Borrowable[] array;

    DVD dvd1 = new DVD();
    DVD dvd2 = new DVD();
    Book book1 = new Book();
    Book book2 = new Book();

    myCar.add(book2);
    myCar.add(dvd1);
    myCar.add(book1);
    myCar.add(dvd2);

    array = myCar.getOverDueBooks(new Date(115, 03, 23));
    System.out.println(array);
}

and the errors that I got

Exception in thread "main" java.lang.NullPointerException
at java.lang.reflect.Array.newArray(Native Method)
at java.lang.reflect.Array.newInstance(Array.java:75)
at labb_part_b.ChechOutCart.getOverDueBooks(LabB_Part_B.java:40)
at labb_part_b.LabB_Part_B.main(LabB_Part_B.java:147)
Java Result: 1

I am new in java any idea that you can give me I will appreciate for ever... thanks





How to get Getter and Setter of a Hibernate class via reflexion

I want to have a depper look into java reflection and hibernate. To pass values to a known setter works, but I want to do the same with an unknown setter of a hibernate pojo. I get the mapped class with

PersistentClass mappedClass = session.configuration.getClassMapping(classFromPath.getName());
Table myTable = mappedClass.getTable();
iter = myTable.getColumnIterator();
while(iter.hasNext()) {
     Column myColumn = (Column) iter.next();
     Property myProperty = mappedClass.getProperty(myColumn.getName());
     System.out.println(myProperty.getName());
}

This is my way, to get a specific property. Now, I want to get the propertys getter and setter methods. One way is to get the name, to concate the words get/set with the property names. I don't like that way and want a better solution. I know, there is a function like myProperty.getSetter, but I'm not sure, how to deal with it.

I'm totally wrong? Are there any ways to get the getter/setter methods?





how to autowrap an existing object when creating a clone in javascript?

I want to be able to create a new object that is effectively an alias of an existing object, except with a new method added to the new object that is not added to the original aliased object. I'm new to javascript, so I don't know if something like what I want already exists and/or is easily implimented. To give a simplified example of my use case consider this:

So say I have a shared object foo. For Angular types imagine a service or factory. It looks like this:

var foo(){
    var array: {},
    updateArray: function(value){ array.push(value)},
    saveFoo: function(parameters){
         //save logic
    }
}

say I get sick of constantly passing huge arrays of parameters to foo's save method, so I decide to add a wrapper to foo with some extra logic to make my life easier

function addSaveableParameters(foo){
      var savedParams={}
      foo.setParam = function(parameter){
          savedParams.push(parameter);
      }
      foo.save = function(){
          foo.save(savedParams);
      }

      return foo
}

foo=addSaveableParameters(foo);

now If I save a parameter one at a time to foo by simply calling my little helper function to add the saveParameter method.

However, imagine if foo was a shared object, or in angular terms a service/factory. If I call addSavableParameters I'm modifying the one version of foo everyone has. More importantly if I have two people that are using my foo service and they each call saveParameters they will both save a parameter to the same shared foo object, which will likely cause them both to be confused when they call save() and find a second parameter they never added exists on foo.

One option to handle this would be to clone foo. However, the original shared foo had an array that others could modify. Perhaps we want to be aware of changes to the array made by others. By cloning foo I create a new instance which has a mere copy of foo's array as of the time it was cloned, it doesn't stay up to date with new changes to the original shared foo's array.

If I wanted to both stay up to date with changes to Foo's array and have my own separate version of savedParameters I could wrap foo instead:

function addSaveableParameters(foo){

      var newFoo={
          savedParams: {},
          setParam: function(parameter){
               savedParams.push(parameter);
          },
          save: function(){
             foo.save(savedParams);
          },
          save: function(parameters){
               foo.save(parameters);
          },
          updateArray: function(value){
               foo.updateArray(value);
          }
        }

   return newFoo;
}

foo=addSaveableParameters(foo);

now I can create my own version of foo, which reflects all changes to the old foo and can generally be used as if it was an alias to the old foo, but which allows me to set saved parameters only on my version of foo.

However, I had to manually wrap functions to do it. If I have a really large object I may find myself wrapping dozens of functions. I also need to know every function foo has ahead of time so I can create a wrapper to it. If someone decides to add a new method to foo later my wrapper won't have the new method.

Is there a convenient way in javascript to make this sort of wrapper logic occur automatically without being written to a specific object? So I can simply call wrapper(foo) and I'll get back an object with all of foos methods and variables, which are still aliased to foo, but where I can add methods which only exist on my version of the wrapped foo object?





Approach doing the same stuff on different objects

I am currently making a library which is an utility for me to handle something which is not associated with the question (I am implicitly not saying the subject because it is not really important), however it does use reflection.

I am retrieving all declared and inherited methods from a class, which currently works fine and is not the issue. But the thing is, I need to do this as well for sub-classes since those inherit over like methods do (however you cannot override those like methods).

The problem that I am facing that it will use the same algorithm but there will be on difference, instead of calling clazz.getDeclaredMethods() I need to call clazz.getMethods. What is the best way too approach this, and I kind of need to return Class[] and Method[] in the method signature as well.

Normally I would look for a shared superclass, but in this case I prefer to the have Class[] and Method[] accordingly. For starters, I did some research and found some shared superclasses:

  • GenericDeclaration
  • AnnotatedElement

Since I need both Class[] and Method[] arrays I am thinking something like generics, so the method would look like:

public static <T extends GenericDecleration> T[] getT () {

}

But how would I detect whether I need to call getDeclaredMethods or getDeclaredClasses?

What is the best approach on how to do this without duplicating a lot of code? I really tried to explain myself here, but if it is still unclear what I am doing please feel free to ask away!

Thank you very much in advance!





Building .Net Code Analysis Tool

I am looking to create .net code analysis tool based on custom rules. i am going to use reflection to read entire code. Is there any way to read number of line consumed in class or method using reflection or any other assembly.

I am thinking to use some opensource tool so i can do modification in it but unable to find it on Google.

Suggestions are welcome! thx





mercredi 22 avril 2015

Assigning properties using RTTI without knowing what type the property is

I have some object newObject with unknown properties and I want to be able to assign values to its properties without knowing what type the property is.

The best I can do so far is

vCtx := TRttiContext.Create;
vType := vCtx.GetType(newObject.ClassType);

for vProp in vType.GetProperties do
begin    
    vPropValue := 'Test Value';

    val := TValue.From<String>( vPropValue);

    vProp.SetValue( newObject , val );
end;

Of course, this assumes that the properties are of type string

How do I make this more general?





Is there a simple way to generically parse data from strings for child class properties of differing types in C#?

I have a base class

abstract public class containerClass {
    protected containerClass () {
        // do stuff
    }

    abstract protected void parseData() {
        // do the stuff I'm mentioning later
    }

}

and child classes

public class childClassOne : containerClass {
    public childClassOne () : base () {
        var1S = "99";
        var2S = "88.3";
        var3S = "2015-04-22T15:55:25.2625065-07:00";
    }
    public int var1 {get: protected set;}
    public double var2 {get: protected set;}
    public DateTime var3 {get: protected set;}

    public string var1S {get: protected set;}
    public string var2S {get: protected set;}
    public string var3S {get: protected set;}
}

and

public class childClassTwo : containerClass {
    public childClassTwo () : base () {
        var1S = "99.22";
        var2S = "88.3";
        var3S = "43.44";
    }
    public double var1 {get: protected set;}
    public double var2 {get: protected set;}
    public double var3 {get: protected set;}

    public string var1S {get: protected set;}
    public string var2S {get: protected set;}
    public string var3S {get: protected set;}
}

What I want to do is define parseData in the parent class to iterate through the properties when it's called by a child class and parse the strings for relevant data.

Order needs to be preserved. And the strings might be external data, not properties or fields of these classes.

My current thoughts in pseudo-code are something like:

for (property prop in thisClass)
{
    typeof(prop) temp;
    if (typeof(prop).tryParse(var1S, temp))
        prop = temp;
}

All of the class I'm looking at have a tryParse method with two input variables. Can what I'm trying to do work? If so, how can I iterate over the properties in an unambiguous order?





Adding a custom attribute to a return value using a ParameterBuilder; attribute doesn't show when reflected -- why?

I think my question title is a bit confusing, so let me clarify. For my purposes, I'm applying a MarshalAsAttribute to parameters and return types.

(Note: Initially I didn't think this was working at all, but this question here lead me to post this question: System.Reflection.Emit - How to add attribute to return type definition?)

So let's say I'm dynamically creating a delegate type for a method with this signature:

[return: MarshalAs(UnmanagedType.I1)]
internal static extern Boolean SomeFunction([MarshalAs(UnmanagedType.LPStr)] string argument);

With code similar to the following, I can do this fine both for the function arguments and for the return type (note I'm omitting a bunch here for brevity):

var currentParameterAttributeBuilder = methodBuilder.DefineParameter(parameterPosition, currentParameterAttributes,
                    parameterName);
var attributeParams = new Type[] { typeof(UnmanagedType) };
var attributeConstructorInfo = typeof(MarshalAsAttribute).GetConstructor(attributeParams);
var customParameterAttribute = new CustomAttributeBuilder(attributeConstructorInfo, new object[] { currentArgument.MarshallingType });
currentParameterAttributeBuilder.SetCustomAttribute(customParameterAttribute);

However, when I go to check via reflection that the attributes exist, such as in the following:

// This works and retrieves the MarshalAs attribute
var argumentCustomAttributes = param.GetCustomAttributes(typeof(MarshalAsAttribute), false);
// This doesn't work; it doesn't 'see' the MarshalAs attribute 
var returnCustomAttributes = type.GetMethod("Invoke").ReturnType.GetCustomAttributes(typeof(MarshalAsAttribute), false);

So basically, the attribute for the return type can't be viewed via reflection, but it is in fact applied, as seen in this .NET Reflector screenshot (this signature differs from above but demonstrates my point):

example image <-- I don't have enough reputation to embed images, sorry.

I'm just curious if anyone knows why this is, as I spent quite a bit of time struggling with it before I stumbled across that other post and realized it was actually being applied correctly. Hopefully I've formatted this correctly; it's my first time posting.





Scala class method to function with class instance as parameter

I'm pretty sure what I'd like to do is probably not possible and not a good idea anyway. Nonetheless, here it is.

I would like to find a generic way of transforming any method on any class into a function that takes as arguments an instance of the class and the parameters of the method and calls the method on the instance with the specified parameters (which is basically how method calls work at a low-level: the object instance is a hidden parameter pushed by the compiler on the stack frame)

Example:

Given

class A { def foo(param1: Type1): TypeN } 

I would like to have something like:

def functor[X](methodName: String): (obj: X, methodParams: Types*) => TypeN

Such that:

// Type (obj: A, param1: Type1) => TypeN 
val fooFn      = functor[A]("foo")
val res: TypeN = fooFn(new A, new Type1)

Which would allow something like:

def flip[A, B, C](fn: A => B => C): B => A => C = (b: B) => (a: A) => fn(a)(b)

// Type (param1: Type1) => (obj: A) => TypeN
val fooFl = flip(fooFn.curried)
List(new A, new A).map(fooFl(new Type1) _)

One example where something like that could be useful follows:

Imagine you have:

val divide = (i: Int) => Try(2/i).toOption

List(1, 0).map(i => divide(i).getOrElse(0))

but you'd like an arguably cleaner:

import OptionUtils.getOrElse

List(1, 0).map(getOrElse(0) _ compose divide)

Now, I've defined that getOrElse manually as:

object OptionUtils {
    def getOrElse[A](default: A)(option: Option[A]) = option.getOrElse(default)
}

But would like to be able to do automatically define such a methods for all (or any given selection) of methods in a specified class. Ideally I'd have something like:

val optionUtils: Utils[Option] = Utils(Option, List("getOrElse", "or"))

optionUtils.getOrElse(None, 1)   // = 1
optionUtils.getOrElseFl(1)(None) // = 1

Any suggestions/comments?





How to extract annotation arguments into external file?

I have following class.

public class MultipartFileWrapper {
    @Extensions({".jpg",".png",".gif",".bmp",".mp4"})
    MultipartFile multipartFile;  
    ...
}

Now I want to extract formats to configuration file. But I don't understand how to replace

@Extensions({".jpg",".png",".gif",".bmp",".mp4"})

I want to rewrite it something like this:

public class MultipartFileWrapper {
        @Extensions(readFormatsFromFile())
        MultipartFile multipartFile;  
        ...
    }

formats should takes from external file with the following content:

.jpg,.png,.gif,.bmp,.mp4

Does java allow do this?





Java - Pass private class to a method

So I have a neat little function which I can use to construct objects when my functions don't know what classes they'll be dealing with. (Yes I do have some nice uses for this before Soritos or anyone else wants to tell me I'm illogical)

public static Object Construct(Class type, Class[] params, Object[] values){
    //Create an object of any class
    try{
       Constructor con = type.getConstructor(params);
       Object o = con.newInstance(values);
       return o;
    }
    catch(Exception e){
       System.out.println("CONSTRUCTOR EXCEPTION"); 
       return null;
    }
}

Anyway I have a class declared within another class file that I want the main class to be able to pass to this function.

public class aClass {
   public aClass(String S, String s){
      Class c = otherClass.class;
      Object o = Functions.Construct(c, new Class[]{String.class, String.class}, new Object[]{S, s});
   }    
}

class otherClass{   
    public otherClass(String arg1, String arg2){}
}

But with this I get an exception. Is this because otherClass is not visible to my constructor function outside of this class?





I'm creating a datareader from a SqlCommand and I currently store this information in a class with the following

    private object PopulateObjectWithFields(SqlDataReader read, Type className)
    {
        var gd = Activator.CreateInstance(className);
        for (int i = 0; i < read.FieldCount; i++)
        {
            var type = gd.GetType();

            var fi = type.GetField(read.GetName(i));
            if (fi != null)
            {
                if (!Convert.IsDBNull(read[i]))
                {
                    try
                    {
                        fi.SetValue(gd, read[i]);
                    }
                    catch
                    {
                        throw new Exception(string.Format("Unable to set {0}. Class type {1}. DB Type {2}", read.GetName(i), fi.FieldType.Name, read[i].GetType().Name));
                    }
                }
            }
            else
            {
                var pi = type.GetProperty(read.GetName(i));
                if (pi != null)
                {
                    if (!Convert.IsDBNull(read[i]))
                    {
                        try
                        {
                            pi.SetValue(gd, read[i]);
                        }
                        catch
                        {
                            throw new Exception(string.Format("Unable to set {0}. Class type {1}. DB Type {2}", read.GetName(i), fi.FieldType.Name, read[i].GetType().Name));
                        }
                    }
                }
            }
        }
        return gd;
    }

This works perfectly. What I would like now is to put it in a List<class>, but I can't seem to get it right to create a List<class> dynamically.

Can someone maybe help me out with the syntax?

var MyList = List<MyClass> //This should be dynamically created

using(var reader = cmd.ExecuteReader())
{
      while (reader.Read())
      {
           MyList.Add(PopulateObjectWithFields(read, MyClass));
      }
}





How to cast a String value to an Enum value by Class?

I have the following class:

public class EnumContainer{

    private Class<?> enumClass;
    //GET, SET

    public EnumContainer(Class<?> clazz){
        this.enumClass = clazz;
    }

    public boolean tryCast(String value){
        //Here I should try to cast the String to the Enum by enumClass field

        //return true if cast was successfull
        //false otherwise
    }
}

Is it even possible in Java to perform such casting?





java - retrive class loaded inside method?

class test{
     void method(){
          javax.swing.JOptionPane.showMessageDialog(null,"test");
     }
}

I don't know it's asked before or not.
how to get class javax.swing.JOptionPane?
i have been using reflection

Class cls=Class.forName("test");
Field[]field=cls.getDeclaredFields();
for(Field f : field)
{
    System.out.println(f.getName());
}

but, it doesn.t print anithing.





mardi 21 avril 2015

Would reflection be the best method of searching for a value of a specific property in a list of Objects?

I have a Class with the following:

public class TestClass {
    string Account1 {get;set;}
    string Account2 {get;set;}
    string Account3 {get;set;}
}

What I would like is to be able to have a method that is similar to the following:

public TestClass[] GetTestClass(string value, string AccountName)

where i can pass in a value say "John" and the AccountName would be "Account1"

and it will go through a list of TestClass and return an array or list of TestClass objects where there exists a value "John" in the Property "Account1"

Is there a better method of doing this or any thoughts would help.

Note: This is a model based of a SQL Table





How can I determine the number and type of metaobjects created?

As far as I've seen, metaobjects are of type: Type-Info Data-Info and ObjectCreator.
In a java aplication, how does one determine the number and type of metaobjects created ?
Take for instance the following sample code:

public class Dtest extends Btest
{
    public int aPublicInt;
    private int aPrivateInt;
    public Dtest(int x)
    {
        // …    
    }

    private void OpD1(String s) {
        // …
    }

    public String OpD2(int x){
        // …
    }


}

Type-info: Dtest object, Class object
Data-Info: Integer object aPublicInt , Integer object aPrivateInt, void Object OpD1 , String Object OpD2
ObjectCreator Dtest

Is this correct ?

Could anyne also explain to me what connections there are between the metaobjects ?





Get type of a property from nested class

I have the following classes:

class TopClass
{
    public string ClsProp1 { get; set; }
    public string ClsProp2 { get; set; }

    public SubClass ClsProp3 { get; set; }
}

class SubClass
{
    public string SCProp1 { get; set; }
    public string SCProp2 { get; set; }
}

When I write the following code to return the property type of one of the members it works fine:

System.Reflection.PropertyInfo p = typeof(TopClass).GetProperty("ClsProp1");
Type t = p.PropertyType;

But how do I recursively check the type of the field inside the nested SubClass by name.. I could write a loop that parses the string I need into tokens on the '.' but this seems to have a "code smell" that isn't very elegant. Ultimately what I'd like to do is something like this:

System.Reflection.PropertyInfo p = typeof(TopClass).GetProperty("ClsProp3.SCProp1");
Type t = p.PropertyType;

But I have no idea how to implement that without complicated looping code.

Thanks in advance





Is Reflection needed to apply the correct generic adapter to my object dynamically

I am currently working on a serialization routine which uses a library of generically typed adapters. If the object being serialized is an instance of one of the specific adapters I have, then I need to call that adapter on the object prior to performing my other serialization procedures.

The following code works:

private final static String serialize(Object obj, Map<Class<?>, 
        XmlAdapter<?,?>> classToAdapterMap) throws JAXBException 
{
    Object adaptedObj = null;

    for (Class<?> clazz : classToAdapterMap.keySet()) {
        if (clazz.isInstance(obj)) {
            XmlAdapter<?,?> adapter = classToAdapterMap.get(clazz);
            Class<?>[] argTypes = new Class[] {clazz};
            try {
                Method method = adapter.getClass().getMethod("marshal", argTypes);
                adaptedObj = method.invoke(adapter, obj);
                break;
            } catch (Exception e) {
                // handle method retrieval and invocation related exceptions
            }
        }
    }

    // serialize
}

However, I had originally thought that I would be able to do this more simply, for example with code like:

/* DOES NOT WORK */
private final static String serialize(Object obj, Map<Class<?>, 
        XmlAdapter<?,?>> classToAdapterMap) throws JAXBException 
{
    Object adaptedObj = null;

    for (Class<?> clazz : classToAdapterMap.keySet()) {
        if (clazz.isInstance(obj)) {
            XmlAdapter<?,?> adapter = classToAdapterMap.get(clazz);
            adaptedObj = adapter.marshal(clazz.cast(obj));
            break;
        }
    }

    // serialize
}

Clearly the problem is that the wildcard generically typed adapter isn't guaranteed to handle an object of type clazz. However, I can't indicate that these two are the same by changing the method signature—as I might otherwise do—to private final static <T> String serialize(Object obj, Map<Class<T>, XmlAdapter<?,T>> classToAdapterMap), because the map needs to hold adapters of all different types.

What would be a better way to do this? Or should I stick with the Reflection based solution?

Thanks in advance,

-Dan