Search Results

Search found 1575 results on 63 pages for 'reflection'.

Page 11/63 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • How to add reflection definition to read JSON files in web game

    - by user3728735
    I have a game which I deployed for desktop and Android. I can read JSON data and create my levels, but when it comes to reading JSON files from web app, I get an error that logs, "cannot read the json file". I researched a lot and I found out that I should add my JSON config class to configurations, so I added this line to gameName.gwt.xml, which is in core folder: <extend-configuration-property name="gdx.reflect.include" value="com.las.get.level.LevelConfig"/> But it did not work out. I have no idea where should I place this line or where I should change to make my web app work, so I can read JSON files.

    Read the article

  • How to add reflection definition to read json files on web game

    - by user3728735
    I have a game which I deployed for desktop and android, I can read json data and create my levels, but the problem is, when it comes to reading json files from web app, I get an error that logs, cannot read the json file, I researched a lot and I found out that I should add my json config class to configurations, I added this line to gameName.gwt.xml, which is in core folder <extend-configuration-property name="gdx.reflect.include" value="com.las.get.level.LevelConfig"/> but it did not work out too, I have no idea where should I place this line, or where should I change to make my web app work, so I can read json files

    Read the article

  • Upon Reflection

    - by foxjazz
    During my tenure at the last company, I didn't let my career stagnate as others have and as time moved along.When at work or home, spend 10% of your time learning something new about some aspect or segway of your job so that your skills are marketable in case you lose it. From experience let me reinforce that it pays off. It pays off in your current job because of the education received and the competence increase of your skills which applied will bring recognition.In these days and times, loyalty to a company is truly at an end. However many companies do care about cultivating their employees which creates a brand of loyalty that can't be replaced. Old companies with the Corp. mentality (or because of the corp. mentality) ever decrease their budgets on organizational sections and thereby do a RIF as a matter of business.The mistakes they make during this process can be risky. But who am I, but a lowly ole programmer, to judge risk. If you are laid off, be friendly with your past manager, and based on simple questions and help, give whatever help you can over the phone even though you are under no obligation to do so.It is also quite possible that there are opportunities to make at home with a new company in the future. Just remember that when inquiring about a position, take advantage of the training that is offered, and keep yourself emotionally and educationally fit.Talk soon,foxjazz

    Read the article

  • PHP GD Reflection with original picture on top

    - by Steve Thomas
    Hi, I have stumbled upon a nice PHP library that uses GD to generate a reflection of a picture. I tried to modify the way so it also display the original image above its reflection to not have to align them in HTML. The script can be found there : http://reflection.corephp.co.uk/v3.php Any idea if this can be done easily ? With my tests, the alpha gradient effect wasnt applied at all. Thank you in advance.

    Read the article

  • Actionscript 3 reflection class questions

    - by VPDD
    I found this reflection class: http://www.adobe.com/devnet/flash/articles/reflect_class_as3.html However, I have some questions about it. Let´s say I have a moviclip named “ref_mc”, to add a reflection I use: import com.pixelfumes.reflect.*; var r1:Reflect = new Reflect({mc:ref_mc, alpha:50, ratio:50, distance:0, updateTime:0, reflectionDropoff:1}); Now, the questions: 1) How do I update the parameters for the reflection r1 after it is created? 2) Is there a way to check whether the movieclip “ref_mc” already has a reflection? 3) Anyone has the .fla for the example with bars adjustments and code sample shown on the page (it is not on the download .zip)? Thanks in advance.

    Read the article

  • Dynamic Paging and Sorting

    - by Ricardo Peres
    Since .NET 3.5 brought us LINQ and expressions, I became a great fan of these technologies. There are times, however, when strong typing cannot be used - for example, when you are developing an ObjectDataSource and you need to do paging having just a column name, a page index and a page size, so I set out to fix this. Yes, I know about Dynamic LINQ, and even talked on it previously, but there's no need to add this extra assembly. So, without further delay, here's the code, in both generic and non-generic versions: public static IList ApplyPagingAndSorting(IEnumerable enumerable, Type elementType, Int32 pageSize, Int32 pageIndex, params String [] orderByColumns) { MethodInfo asQueryableMethod = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(m = (m.Name == "AsQueryable") && (m.ContainsGenericParameters == false)).Single(); IQueryable query = (enumerable is IQueryable) ? (enumerable as IQueryable) : asQueryableMethod.Invoke(null, new Object [] { enumerable }) as IQueryable; if ((orderByColumns != null) && (orderByColumns.Length 0)) { PropertyInfo orderByProperty = elementType.GetProperty(orderByColumns [ 0 ]); MemberExpression member = Expression.MakeMemberAccess(Expression.Parameter(elementType, "n"), orderByProperty); LambdaExpression orderBy = Expression.Lambda(member, member.Expression as ParameterExpression); MethodInfo orderByMethod = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m = m.Name == "OrderBy").ToArray() [ 0 ].MakeGenericMethod(elementType, orderByProperty.PropertyType); query = orderByMethod.Invoke(null, new Object [] { query, orderBy }) as IQueryable; if (orderByColumns.Length 1) { MethodInfo thenByMethod = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m = m.Name == "ThenBy").ToArray() [ 0 ].MakeGenericMethod(elementType, orderByProperty.PropertyType); PropertyInfo thenByProperty = null; MemberExpression thenByMember = null; LambdaExpression thenBy = null; for (Int32 i = 1; i 0) { MethodInfo takeMethod = typeof(Queryable).GetMethod("Take", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType); MethodInfo skipMethod = typeof(Queryable).GetMethod("Skip", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(elementType); query = skipMethod.Invoke(null, new Object [] { query, pageSize * pageIndex }) as IQueryable; query = takeMethod.Invoke(null, new Object [] { query, pageSize }) as IQueryable; } MethodInfo toListMethod = typeof(Enumerable).GetMethod("ToList", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(elementType); IList list = toListMethod.Invoke(null, new Object [] { query }) as IList; return (list); } public static List ApplyPagingAndSorting(IEnumerable enumerable, Int32 pageSize, Int32 pageIndex, params String [] orderByColumns) { return (ApplyPagingAndSorting(enumerable, typeof(T), pageSize, pageIndex, orderByColumns) as List); } List list = new List { new DateTime(2010, 1, 1), new DateTime(1999, 1, 12), new DateTime(1900, 10, 10), new DateTime(1900, 2, 20), new DateTime(2012, 5, 5), new DateTime(2012, 1, 20) }; List sortedList = ApplyPagingAndSorting(list, 3, 0, "Year", "Month", "Day"); SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • Dynamic LINQ in an Assembly Near By

    - by Ricardo Peres
    You may recall my post on Dynamic LINQ. I said then that you had to download Microsoft's samples and compile the DynamicQuery project (or just grab my copy), but there's another way. It turns out Microsoft included the Dynamic LINQ classes in the System.Web.Extensions assembly, not the one from ASP.NET 2.0, but the one that was included with ASP.NET 3.5! The only problem is that all types are private: Here's how to use it: Assembly asm = typeof(UpdatePanel).Assembly; Type dynamicExpressionType = asm.GetType("System.Web.Query.Dynamic.DynamicExpression"); MethodInfo parseLambdaMethod = dynamicExpressionType.GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m = (m.Name == "ParseLambda") && (m.GetParameters().Length == 2)).Single().MakeGenericMethod(typeof(DateTime), typeof(Boolean)); Func filterExpression = (parseLambdaMethod.Invoke(null, new Object [] { "Year == 2010", new Object [ 0 ] }) as Expression).Compile(); List list = new List { new DateTime(2010, 1, 1), new DateTime(1999, 1, 12), new DateTime(1900, 10, 10), new DateTime(1900, 2, 20), new DateTime(2012, 5, 5), new DateTime(2012, 1, 20) }; IEnumerable filteredDates = list.Where(filterExpression); SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • Enhanced Dynamic Filtering

    - by Ricardo Peres
    Remember my last post on dynamic filtering? Well, this time I'm extending the code in order to allow two levels of querying: Match type, represented by the following options: public enum MatchType { StartsWith = 0, Contains = 1 } And word match: public enum WordMatch { AnyWord = 0, AllWords = 1, ExactPhrase = 2 } You can combine the two levels in order to achieve the following combinations: MatchType.StartsWith + WordMatch.AnyWord Matches any record that starts with any of the words specified MatchType.StartsWith + WordMatch.AllWords Not available: does not make sense, throws an exception MatchType.StartsWith + WordMatch.ExactPhrase Matches any record that starts with the exact specified phrase MatchType.Contains + WordMatch.AnyWord Matches any record that contains any of the specified words MatchType.Contains + WordMatch.AllWords Matches any record that contains all of the specified words MatchType.Contains + WordMatch.ExactPhrase Matches any record that contains the exact specified phrase Here is the code: public static IList Search(IQueryable query, Type entityType, String dataTextField, String phrase, MatchType matchType, WordMatch wordMatch, Int32 maxCount) { String [] terms = phrase.Split(' ').Distinct().ToArray(); StringBuilder result = new StringBuilder(); PropertyInfo displayProperty = entityType.GetProperty(dataTextField); IList searchList = null; MethodInfo orderByMethod = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m = m.Name == "OrderBy").ToArray() [ 0 ].MakeGenericMethod(entityType, displayProperty.PropertyType); MethodInfo takeMethod = typeof(Queryable).GetMethod("Take", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(entityType); MethodInfo whereMethod = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m = m.Name == "Where").ToArray() [ 0 ].MakeGenericMethod(entityType); MethodInfo distinctMethod = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m = m.Name == "Distinct" && m.GetParameters().Length == 1).Single().MakeGenericMethod(entityType); MethodInfo toListMethod = typeof(Enumerable).GetMethod("ToList", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(entityType); MethodInfo matchMethod = typeof(String).GetMethod ( (matchType == MatchType.StartsWith) ? "StartsWith" : "Contains", new Type [] { typeof(String) } ); MemberExpression member = Expression.MakeMemberAccess ( Expression.Parameter(entityType, "n"), displayProperty ); MethodCallExpression call = null; LambdaExpression where = null; LambdaExpression orderBy = Expression.Lambda ( member, member.Expression as ParameterExpression ); switch (matchType) { case MatchType.StartsWith: switch (wordMatch) { case WordMatch.AnyWord: call = Expression.Call ( member, matchMethod, Expression.Constant(terms [ 0 ]) ); where = Expression.Lambda ( call, member.Expression as ParameterExpression ); for (Int32 i = 1; i ()); where = Expression.Lambda ( Expression.Or ( where.Body, exp ), where.Parameters.ToArray() ); } break; case WordMatch.ExactPhrase: call = Expression.Call ( member, matchMethod, Expression.Constant(phrase) ); where = Expression.Lambda ( call, member.Expression as ParameterExpression ); break; case WordMatch.AllWords: throw (new Exception("The match type StartsWith is not supported with word match AllWords")); } break; case MatchType.Contains: switch (wordMatch) { case WordMatch.AnyWord: call = Expression.Call ( member, matchMethod, Expression.Constant(terms [ 0 ]) ); where = Expression.Lambda ( call, member.Expression as ParameterExpression ); for (Int32 i = 1; i ()); where = Expression.Lambda ( Expression.Or ( where.Body, exp ), where.Parameters.ToArray() ); } break; case WordMatch.ExactPhrase: call = Expression.Call ( member, matchMethod, Expression.Constant(phrase) ); where = Expression.Lambda ( call, member.Expression as ParameterExpression ); break; case WordMatch.AllWords: call = Expression.Call ( member, matchMethod, Expression.Constant(terms [ 0 ]) ); where = Expression.Lambda ( call, member.Expression as ParameterExpression ); for (Int32 i = 1; i ()); where = Expression.Lambda ( Expression.AndAlso ( where.Body, exp ), where.Parameters.ToArray() ); } break; } break; } query = orderByMethod.Invoke(null, new Object [] { query, orderBy }) as IQueryable; query = whereMethod.Invoke(null, new Object [] { query, where }) as IQueryable; if (maxCount != 0) { query = takeMethod.Invoke(null, new Object [] { query, maxCount }) as IQueryable; } searchList = toListMethod.Invoke(null, new Object [] { query }) as IList; return (searchList); } And this is how you'd use it: IQueryable query = ctx.MyEntities; IList list = Search(query, typeof(MyEntity), "Name", "Ricardo Peres", MatchType.Contains, WordMatch.ExactPhrase, 10 /*0 for all*/); SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • NDepend 4 – First Steps

    - by Ricardo Peres
    Introduction Thanks to Patrick Smacchia I had the chance to test NDepend 4. I can only say: awesome! This will be the first of a series of posts on NDepend, where I will talk about my discoveries. Keep in mind that I am just starting to use it, so more experienced users may find these too basic, I just hope I don’t say anything foolish! I must say that I am in no way affiliated with NDepend and I never actually met Patrick. Installation No installation program – a curious decision, I’m not against it -, just unzip the files to a folder and run the executable. It will optionally register itself with Visual Studio 2008, 2010 and 11 as well as RedGate’s Reflector; also, it automatically looks for updates. NDepend can either be used as a stand-alone program (with or without a GUI) or from within Visual Studio or Reflector. Getting Started One thing that really pleases me is the Getting Started section of the stand-alone, with links to pages on NDepend’s web site, featuring detailed explanations, which usually include screenshots and small videos (<5 minutes). There’s also an How do I with hierarchical navigation that guides us to through the major features so that we can easily find what we want. Usage There are two basic ways to use NDepend: Analyze .NET solutions, projects or assemblies; Compare two versions of the same assembly. I have so far not used NDepend to compare assemblies, so I will first talk about the first option. After selecting a solution and some of its projects, it generates a single HTML page with an highly detailed report of the analysis it produced. This includes some metrics such as number of lines of code, IL instructions, comments, types, methods and properties, the calculation of the cyclomatic complexity, coupling and lots of others indicators, typically grouped by type, namespace and assembly. The HTML also includes some nice diagrams depicting assembly dependencies, type and method relative proportions (according to the number of IL instructions, I guess) and assembly analysis relating to abstractness and stability. Useful, I would say. Then there’s the rules; NDepend tests the target assemblies against a set of more than 120 rules, grouped in categories Code Quality, Object Oriented Design, Design, Architecture and Layering, Dead Code, Visibility, Naming Conventions, Source Files Organization and .NET Framework Usage. The full list can be configured on the application, and an explanation of each rule can be found on the web site. Rules can be validated, violated and violated in a critical manner, and the HTML will contain the violated rules, their queries – more on this later - and results. The HTML uses some nice JavaScript effects, which allow paging and sorting of tables, so its nice to use. Similar to the rules, there are some queries that display results for a number (about 200) questions grouped as Object Oriented Design, API Breaking Changes (for assembly version comparison), Code Diff Summary (also for version comparison) and Dead Code. The difference between queries and rules is that queries are not classified as passes, violated or critically violated, just present results. The queries and rules are expressed through CQLinq, which is a very powerful LINQ derivative specific to code analysis. All of the included rules and queries can be enabled or disabled and new ones can be added, with intellisense to help. Besides the HTML report file, the NDepend application can be used to explore all analysis results, compare different versions of analysis reports and to run custom queries. Comparison to Other Analysis Tools Unlike StyleCop, NDepend only works with assemblies, not source code, so you can’t expect it to be able to enforce brackets placement, for example. It is more similar to FxCop, but you don’t have the option to analyze at the IL level, that is, other that the number of IL instructions and the complexity. What’s Next In the next days I’ll continue my exploration with a real-life test case. References The NDepend web site is http://www.ndepend.com/. Patrick keeps an updated blog on http://codebetter.com/patricksmacchia/ and he regularly monitors StackOverflow for questions tagged NDepend, which you can find on http://stackoverflow.com/questions/tagged/ndepend. The default list of CQLinq rules, queries and statistics can be found at http://www.ndepend.com/DefaultRules/webframe.html. The syntax itself is described at http://www.ndepend.com/Doc_CQLinq_Syntax.aspx and its features at http://www.ndepend.com/Doc_CQLinq_Features.aspx.

    Read the article

  • Dynamic Filtering

    - by Ricardo Peres
    Continuing my previous posts on dynamic LINQ, now it's time for dynamic filtering. For now, I'll focus on string matching. There are three standard operators for string matching, which both NHibernate, Entity Framework and LINQ to SQL recognize: Equals Contains StartsWith EndsWith So, if we want to apply filtering by one of these operators on a string property, we can use this code: public enum MatchType { StartsWith = 0, EndsWith = 1, Contains = 2, Equals = 3 } public static List Filter(IEnumerable enumerable, String propertyName, String filter, MatchType matchType) { return (Filter(enumerable, typeof(T), propertyName, filter, matchType) as List); } public static IList Filter(IEnumerable enumerable, Type elementType, String propertyName, String filter, MatchType matchType) { MethodInfo asQueryableMethod = typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public).Where(m = (m.Name == "AsQueryable") && (m.ContainsGenericParameters == false)).Single(); IQueryable query = (enumerable is IQueryable) ? (enumerable as IQueryable) : asQueryableMethod.Invoke(null, new Object [] { enumerable }) as IQueryable; MethodInfo whereMethod = typeof(Queryable).GetMethods(BindingFlags.Public | BindingFlags.Static).Where(m = m.Name == "Where").ToArray() [ 0 ].MakeGenericMethod(elementType); MethodInfo matchMethod = typeof(String).GetMethod ( (matchType == MatchType.StartsWith) ? "StartsWith" : (matchType == MatchType.EndsWith) ? "EndsWith" : (matchType == MatchType.Contains) ? "Contains" : "Equals", new Type [] { typeof(String) } ); PropertyInfo displayProperty = elementType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); MemberExpression member = Expression.MakeMemberAccess(Expression.Parameter(elementType, "n"), displayProperty); MethodCallExpression call = Expression.Call(member, matchMethod, Expression.Constant(filter)); LambdaExpression where = Expression.Lambda(call, member.Expression as ParameterExpression); query = whereMethod.Invoke(null, new Object [] { query, where }) as IQueryable; MethodInfo toListMethod = typeof(Enumerable).GetMethod("ToList", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(elementType); IList list = toListMethod.Invoke(null, new Object [] { query }) as IList; return (list); } var list = new [] { new { A = "aa" }, new { A = "aabb" }, new { A = "ccaa" }, new { A = "ddaadd" } }; var contains = Filter(list, "A", "aa", MatchType.Contains); var endsWith = Filter(list, "A", "aa", MatchType.EndsWith); var startsWith = Filter(list, "A", "aa", MatchType.StartsWith); var equals = Filter(list, "A", "aa", MatchType.Equals); Perhaps I'll write some more posts on this subject in the near future. SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • Yet Another Way To Create An Object

    - by Ricardo Peres
    After I wrote this post, I come up with yet another way to create an object... Here it is: Stopwatch watch = new Stopwatch(); ConstructorInfo ci = typeof(StringBuilder).GetConstructor(new Type[0]); NewExpression expr = Expression.New(ci); Func<StringBuilder> func = Expression.Lambda(typeof(Func<StringBuilder>), expr).Compile() as Func<StringBuilder>; watch.Start(); for (Int32 i = 0; i < 100; ++i) { StringBuilder builder = func(); } Int64 time4 = watch.ElapsedTicks; watch.Reset(); I know of only one other way, which is by using CodeDOM. If you know of any other ways to create an object, let me know! SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • Yet Yet Another Way To Create An Object

    - by Ricardo Peres
    Yep, there's still another one: FormatterServices. This one allows one to create an object without running it's constructor... it is used by some of our good friends serializers. Stopwatch watch = new Stopwatch(); for (Int32 i = 0; i Beware, though: because the constructor isn't run (and remember that all fields that are initialized inline are also in fact initialized in the constructor), the object's state may be invalid. Enough object construction for now... SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.0.320/scripts/clipboard.swf'; SyntaxHighlighter.brushes.CSharp.aliases = ['c#', 'c-sharp', 'csharp']; SyntaxHighlighter.all();

    Read the article

  • Where can I get a list or data base of light reflectance values for different materials?

    - by mikidelux
    I'm implementing lighting for a WebGL app but I'm not an artist so I don't know how to generate or where to obtain a list of materials with its values (diffuse, specular, ambient and shininess). I've been searching a lot but with no luck. Is there any list or DB I might have overlooked? Any common repository or something similar? Thanks in advance. Note: English is not my main language, let me know if you don't understand something and I'll try to rephrase it.

    Read the article

  • Type hinting for functions in Clojure

    - by mikera
    I'm trying to resolve a reflection warning in Clojure that seems to result from the lack of type inference on function return values that are normal Java objects. Trivial example code that demonstrates the issue: (set! *warn-on-reflection* true) (defn foo [#^Integer x] (+ 3 x)) (.equals (foo 2) (foo 2)) => Reflection warning, NO_SOURCE_PATH:10 - call to equals can't be resolved. true What is the best way to solve this? Can this be done with type hints?

    Read the article

  • Strange Effect with Overridden Properties and Reflection

    - by naacal
    I've come across a strange behaviour in .NET/Reflection and cannot find any solution/explanation for this: Class A { public string TestString { get; set; } } Class B : A { public override string TestString { get { return "x"; } } } Since properties are just pairs of functions (get_PropName(), set_PropName()) overriding only the "get" part should leave the "set" part as it is in the base class. And this is just what happens if you try to instanciate class B and assign a value to TestString, it uses the implementation of class A. But what happens if I look at the instantiated object of class B in reflection is this: PropertyInfo propInfo = b.GetType().GetProperty("TestString"); propInfo.CanRead ---> true propInfo.CanWrite ---> false(!) And if I try to invoke the setter from reflection with: propInfo.SetValue("test", b, null); I'll even get an ArgumentException with the following message: Property set method not found. Is this as expected? Because I don't seem to find a combination of BindingFlags for the GetProperty() method that returns me the property with a working get/set pair from reflection.

    Read the article

  • How can I map a String to a function in Java?

    - by Bears will eat you
    Currently, I have a bunch of Java classes that implement a Processor interface, meaning they all have a processRequest(String key) method. The idea is that each class has a few (say, <10) member Strings, and each of those maps to a method in that class via the processRequest method, like so: class FooProcessor implements Processor { String key1 = "abc"; String key2 = "def"; String key3 = "ghi"; // and so on... String processRequest(String key) { String toReturn = null; if (key1.equals(key)) toReturn = method1(); else if (key2.equals(key)) toReturn = method2(); else if (key3.equals(key)) toReturn = method3(); // and so on... return toReturn; } String method1() { // do stuff } String method2() { // do other stuff } String method3() { // do other other stuff } // and so on... } You get the idea. This was working fine for me, but now I need a runtime-accessible mapping from key to function; not every function actually returns a String (some return void) and I need to dynamically access the return type (using reflection) of each function in each class that there's a key for. I already have a manager that knows about all the keys, but not the mapping from key to function. My first instinct was to replace this mapping using if-else statements with a Map<String, Function>, like I could do in Javascript. But, Java doesn't support first-class functions so I'm out of luck there. I could probably dig up a third-party library that lets me work with first-class functions, but I haven't seen any yet, and I doubt that I need an entire new library. I also thought of putting these String keys into an array and using reflection to invoke the methods by name, but I see two downsides to this method: My keys would have to be named the same as the method - or be named in a particular, consistent way so that it's easy to map them to the method name. This seems WAY slower than the if-else statements I have right now. Efficiency is something of a concern because these methods will tend to get called pretty frequently, and I want to minimize unnecessary overhead. TL; DR: I'm looking for a clean, minimal-overhead way to map a String to some sort of a Function object that I can invoke and call (something like) getReturnType() on. I don't especially mind using a 3rd-party library if it really fits my needs. I also don't mind using reflection, though I would strongly prefer to avoid using reflection every single time I do a method lookup - maybe using some caching strategy that combines the Map with reflection. Thoughts on a good way to get what I want? Cheers!

    Read the article

  • How to create a generic list in this wierd case in c#

    - by Marc Bettex
    Hello, In my program, I have a class A which is extended by B, C and many more classes. I have a method GetInstance() which returns a instance of B or C (or of one of the other child), but I don't know which one, so the return type of the method is A. In the method CreateGenericList(), I have a variable v of type A, which is in fact either a B, a C or another child type and I want to create a generic list of the proper type, i.e. List<B> if v is a B or List<C> if v is a C, ... Currently I do it by using reflection, which works, but this is extremely slow. I wanted to know if there is another way to to it, which doesn't use reflection. Here is an example of the code of my problem: class A { } class B : A { } class C : A { } // More childs of A. class Program { static A GetInstance() { // returns an instance of B or C } static void CreateGenericList() { A v = Program.GetInstance(); IList genericList = // Here I want an instance of List<B> or List<C> or ... depending of the real type of v, not a List<A>. } } I tried the following hack. I call the following method, hoping the type inferencer will guess the type of model, but it doesn't work and return a List<A>. I believe that because c# is statically typed, T is resolved as A and not as the real type of model at runtime. static List<T> CreateGenericListFromModel<T>(T model) where T : A { return new List<T> (); } Does anybody have a solution to that problem that doesn't use reflection or that it is impossible to solve that problem without reflection? Thank you very much, Marc

    Read the article

  • Define interface for loading custom UserControls through reflection

    - by Tim
    I'm loading custom user controls into my form using reflection. I would like all my user controls to have a "Start" and "End" method so they should all be like: public interface IStartEnd { void Start(); void End(); } public class AnotherControl : UserControl, IStartEnd { public void Start() { } public void End() { } } I would like an interface to load through reflection, but the following obviously wont work as an interface cannot inherit a class: public interface IMyUserControls : UserControl, IInit, IDispose { }

    Read the article

  • How do I get class of an internal static class in another assembly?

    - by Echiban
    I have a class C in Assembly A like this: internal class C { internal static string About_Name { get { return "text"; } ... } I have about 20 such static properties. Is there a way, in an outside assembly, without using friend assembly attribute (.Net reflection only), get class C so I can invoke any of the static string properties like this: Class C = <some .Net reflection code>; string expected = C.About_Name; If that is not possible, a .Net reflection code to get the string property value directly will suffice, but not ideal. Thanks in advance!

    Read the article

  • Dynamic object property populator (without reflection)

    - by grenade
    I want to populate an object's properties without using reflection in a manner similar to the DynamicBuilder on CodeProject. The CodeProject example is tailored for populating entities using a DataReader or DataRecord. I use this in several DALs to good effect. Now I want to modify it to use a dictionary or other data agnostic object so that I can use it in non DAL code --places I currently use reflection. I know almost nothing about OpCodes and IL. I just know that it works well and is faster than reflection. I have tried to modify the CodeProject example and because of my ignorance with IL, I have gotten stuck on two lines. One of them deals with dbnulls and I'm pretty sure I can just lose it, but I don't know if the lines preceding and following it are related and which of them will also need to go. The other, I think, is the one that pulled the value out of the datarecord before and now needs to pull it out of the dictionary. I think I can replace the "getValueMethod" with my "property.Value" but I'm not sure. I'm open to alternative/better ways of skinning this cat too. Here's the code so far (the commented out lines are the ones I'm stuck on): using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; public class Populator<T> { private delegate T Load(Dictionary<string, object> properties); private Load _handler; private Populator() { } public T Build(Dictionary<string, object> properties) { return _handler(properties); } public static Populator<T> CreateBuilder(Dictionary<string, object> properties) { //private static readonly MethodInfo getValueMethod = typeof(IDataRecord).GetMethod("get_Item", new [] { typeof(int) }); //private static readonly MethodInfo isDBNullMethod = typeof(IDataRecord).GetMethod("IsDBNull", new [] { typeof(int) }); Populator<T> dynamicBuilder = new Populator<T>(); DynamicMethod method = new DynamicMethod("Create", typeof(T), new[] { typeof(Dictionary<string, object>) }, typeof(T), true); ILGenerator generator = method.GetILGenerator(); LocalBuilder result = generator.DeclareLocal(typeof(T)); generator.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes)); generator.Emit(OpCodes.Stloc, result); int i = 0; foreach (var property in properties) { PropertyInfo propertyInfo = typeof(T).GetProperty(property.Key, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.FlattenHierarchy | BindingFlags.Default); Label endIfLabel = generator.DefineLabel(); if (propertyInfo != null && propertyInfo.GetSetMethod() != null) { generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, i); //generator.Emit(OpCodes.Callvirt, isDBNullMethod); generator.Emit(OpCodes.Brtrue, endIfLabel); generator.Emit(OpCodes.Ldloc, result); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, i); //generator.Emit(OpCodes.Callvirt, getValueMethod); generator.Emit(OpCodes.Unbox_Any, property.Value.GetType()); generator.Emit(OpCodes.Callvirt, propertyInfo.GetSetMethod()); generator.MarkLabel(endIfLabel); } i++; } generator.Emit(OpCodes.Ldloc, result); generator.Emit(OpCodes.Ret); dynamicBuilder._handler = (Load)method.CreateDelegate(typeof(Load)); return dynamicBuilder; } } EDIT: Using Marc Gravell's PropertyDescriptor implementation (with HyperDescriptor) the code is simplified a hundred-fold. I now have the following test: using System; using System.Collections.Generic; using System.ComponentModel; using Hyper.ComponentModel; namespace Test { class Person { public int Id { get; set; } public string Name { get; set; } } class Program { static void Main() { HyperTypeDescriptionProvider.Add(typeof(Person)); var properties = new Dictionary<string, object> { { "Id", 10 }, { "Name", "Fred Flintstone" } }; Person person = new Person(); DynamicUpdate(person, properties); Console.WriteLine("Id: {0}; Name: {1}", person.Id, person.Name); Console.ReadKey(); } public static void DynamicUpdate<T>(T entity, Dictionary<string, object> properties) { foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(typeof(T))) if (properties.ContainsKey(propertyDescriptor.Name)) propertyDescriptor.SetValue(entity, properties[propertyDescriptor.Name]); } } } Any comments on performance considerations for both TypeDescriptor.GetProperties() & PropertyDescriptor.SetValue() are welcome...

    Read the article

  • Modify static data members from another process?

    - by cake
    In .Net, is it possible for process A to modify the values of some static data members from process B? When running under the same AppDomain, it's possible to do so via Reflection, but about doing so between different process? (via Reflection also. I'm not looking to use functions such as Win32::ReadProcessMemory)

    Read the article

  • AS3 (Pixelfumes Reflection Class)

    - by Mick
    Hi I am using a reflection class in my code. I have stripped it right down to the code below. I have a mc on the stage with an instance name of sand. I have tried all combinations and do not get an error BUT i don't get a reflection either. I have been on the forums for the site but cant find any info. Does anyone have any experience with this plugin please ? import com.pixelfumes.reflect.*; new Reflect({mc:sand, alpha:100, ratio:255, distance:0, updateTime:0.2, reflectionAlpha:100, reflectionDropoff:3.64});

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >