mercredi 31 décembre 2014

How to ignore modifiers when invoking methods on run-time - JAVA

I want to look for a specific annotation of every method in a class and if a method with that annotation is found, i would like to invoke it. Also, if it's not found in the current class, a check on all inheriting classes should be made.


My problem is that there might be some methods that are protected, private etc. and I would like to ignore those modifiers and to gain access to all methods (i.e even if it's private etc.)


So this is how I invoke (given is the name of the annotation that I'm looking for:



if (m.isAnnotationPresent(Given.class)) {
m.invoke(instObj, intArgument);
}


(And this is how I check the rest of the class hierarchy - if i made a mistake somewhere, enlighten me please:



Class<?> superC = c.getSuperclass();
while (!(superC.equals(Object.class))) {
handleGiven(instObj, superC, methods, currentSentence,
methodArgument);


when handleGiven is a recursive call.






Type.GetMember is not finding AsEnumerable

The type System.Data.DataTable, when calling GetMembers, does not return AsEnumerable in the results.


To confirm this, I ran:



Dim Query = From MemberInfo As MemberInfo
In GetType(DataTable).GetMembers
Select MemberName = MemberInfo.Name
Order By MemberName
For Each MemberName As String In Query.ToList
Debug.WriteLine(MemberName)
Next


Note that System.Data.DataSetExtensions is added as a reference, and there is a "using" (Imports) for System.Data


I am looking for the right code to get the MemberInfo for AsEnumerable.


Also note that I will not know the Type at runtime, I'm just using this as a concrete example, so I can't hard-code the solution for DataTable. I do realize the problem lies elsewhere, is not specific to DataTable methods, but I think by concrete example of a problem / solution I can extrapolate that to work with every Type.






Why would I need to compile/generate methods/code at runtime?

I'm interested in the theoretical aspect. What is the need in C# for using Codedom/Reflection or Lamda expressions/expression trees for generating code at runtime in a typical day to day programing scenario? not in specialized cases


or in other languages like Ruby, why use monkeypatching for adding/modifying classes at runtime?


How this could be an advantage?






Retrieve "property getter" from the property name

I've been using this method to retrieve a property getter based on the name of the property.



public static Func<object> GetGetterFromProperty(object instance, string propertyName)
{
var propInfo = instance.GetType().GetTypeInfo().GetDeclaredProperty(propertyName);
var deleg = propInfo.GetMethod.CreateDelegate(typeof(Func<object>), instance);
var action = (Func<object>)deleg;
return action;
}


It returns a Func<object> since the type of the property is available only at runtime.


It works perfectly, but ONLY when the property is a reference type. When it's a value type, like int, it throws a System.ArgumentException



Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.







mardi 30 décembre 2014

Determine the length of code programmatically [on hold]

So I was wondering if it is possible to check how many lines of code is when given a delegate. So for example lets say I have this method:



private int Foo()
{
var @string = "string";
var count = @string.Count();
}


The program would would return '2' because the method has 2 lines of code. I was thinking about how to do this using reflection, but I am no master with it. So at the moment I have a function that looks like this:



public static string Measure(this Action del)
{
var timer = new Stopwatch();
var length = // Length of the action
timer.Start();
del.Invoke();
timer.Stop();
return timer.Elapsed.TotalMilliseconds.ToString(CultureInfo.CurrentCulture);
}


And called like this:



Benchmark.Measure(() =>
{
var @string = "string";
var count = @string.Count();
});


So in this case length would be '2'






Refletcion PropertyInfo.GetValue(object) throwing DBNull Exception

I am having a difficult time with what should be a simple bit of code. The code below loops through the properties of a custom class and gets the value from that class object and stuffs it in the data row.



DataRow row = table.NewRow();

foreach(PropertyInfo p in sfa.GetType().GetProperties())
{
row[p.Name] = p.GetValue(sfa);
}


The problem is the error I get. "Cannot set Column 'columnName' to be null. Please use DBNull instead."


The particular column it is choking on is a DateTime type property. I am all good with using DBNull if that's what it wants. I just don't know and can't figure out HOW? How do I tell the row.column intersection that I want to give it DBNull if it doesn't like System.null.


Thanks in advance for your help!






How to retrieve the real type of a Generic type using Java reflection [duplicate]


This question already has an answer here:




suppose the following:



public class Dao<T> {

public Dao() {
}
}

public class Test {

public Test() {
Dao<Person> personDao = new Dao<Person>();
//Get the real type of Dao using reflection, i want to get in this case "Person"
}
}


How can I retrieve the real type of Dao using Java reflection ?






how to perform typecastng at runtime in java?

i am trying to make a client for services exposed through REST.I have multiple number of classes extending a single class.


Now when i send the request and get a response,every time i need to type cast the response for specific class.i am trying to automate this process,can this be achieved at run time?


I am thinking of using generics and reflection but unable to move forward.what i exactly want to achieve is by just mentioning a unique string or say request,i must be able to get exact same response without type casting it with that particular response class.


i know this is not much,but any help is appreciated.Thanks in advance.






Synchronization on an object retrieved via reflection

I'm hooking into a method via the Xposed framework for Android. This effectively allows me to inject my own code into another Android app at runtime and have it run just as if the target app was built with it. Fun stuff. While this is how I'm injecting the code, my question should be independent of Xposed as it's using an extension of the standard Java reflection utilities to retrieve the class references I need.



Class targetClass = XposedHelpers.findClass("fullClassName", targetAppClassLoader);
Object timerField = XposedHelpers.getStaticObjectField(targetClass, "targetFieldName");
// This /should/ synchronize with the actual static field not our local representation of it
synchronized (timerField) {
// Do stuff
}


In the above snippet I'm retrieving a static object field in a class via reflection. Internally, the target app uses synchronized blocks on this field. I need to operate in a similar synchronous manner so I do the same in my own code (link to full code).


Since Java objects are sorta passed by reference I should be retrieving a local reference to the static object in the target app. But do Java synchronized blocks work on reflected objects? And do they work together with non-reflected pre-existing synchronized blocks?


For reference, here is the code for findClass and getStaticObjectField . The former essentially returns a returns a Class<?> from org.external.org.apache.commons.lang3.ClassUtils and the latter (essentially) calls getDeclaredField on the Class<?> parameter, sets the Field to accessible, and returns the result of get(null) on the Field.






Reflect value of []byte

How do I retrieve the []byte value of this interface?



package main

import (
"reflect"
)

func byteInterface() interface{} {
return []byte("foo")
}

func main() {
//var b []byte
i := byteInterface()

switch {
case reflect.TypeOf(i).Kind() == reflect.Slice && (reflect.TypeOf(i) == reflect.TypeOf([]byte(nil))):

default:
panic("should have bytes")
}
}





How can I get the Object from a Field/Class using reflection?

I'm using reflection to get the Field at another Class, but when I try to use the f.set(...) to set a value into the Field, I dont have a Object, only the Class.


I code something similar to this:



Class<?> c = null;

String fieldNameAux = "id";
String classNameAux = "PedV";

try {
c = Class.forName("beans."+classNameAux);
} catch (Exception e){}

Field f = c.getDeclaredField(fieldNameAux);
f.setAccessible(true);

f.set(**something**, ((Edit) objAux).getText();


As I need get the Class and the Field dynamically I can't use something like this (but it works):



Class<?> c = null;

String fieldNameAux = "id";
PedV pedV = new PedV();

c = pedV.getClass();

Field f = c.getDeclaredField(fieldNameAux);
f.setAccessible(true);

f.set(pedV, ((Edit) objAux).getText());


How could I substitute this f.set(pedV, ((Edit) objAux).getText(); for something that works dynamically?


OBS: I'm getting fieldNameAux and classNameAux in a database.






How to use C# extension methods with SmartFormat reflection syntax?

Is it possible to make the following example work with SmartFormat.NET?



void Main()
{
Dictionary<string,string> ps = new Dictionary<string, string>();

ps["Name"] = "Niels";

Smart.Format("{Name.Foo} is my name", ps).Dump();
}


public static class Extensions
{

public static string Foo(this string bar)
{
return bar.ToUpper();
}

}


This will return " is my name" in LinqPad.






java.lang.IllegalArgumentException: Can not set java.lang.String field com.w.state.ProviderSearch.config_URL to java.lang.String

I fail to fill an object with reflection. can you please tell why?



public void setConfig(WyPreferences wyPreferences, String category, String key, String val) {
String normalizedCategory = stringUtils.normalizeFieldNameToCamelCase(category);
String normalizedKey = stringUtils.normalizeFieldNameToUnderScore(key);

try {
Field field1 = WyPreferences.class.getDeclaredField(normalizedCategory);
Object object1 = field1.get(wyPreferences);
if (object1 == null)
{
object1 = field1.getType().newInstance();
}
Field field2 = field1.getType().getDeclaredField(normalizedKey);
Object object2 = field2.get(object1);
if (object2 == null)
{
object2 = field2.getType().newInstance();
}
field2.set(object2, val);
field1.set(object1, object2);
} catch (Exception ex) {
String a = "";
}


category = providerSearch


key =config_URL


where val = "bla"


and with this class:



public class WyPreferences {

public ProviderSearch providerSearch;

public WyPreferences() {
this.providerSearch = new ProviderSearch();
}
}



public ProviderSearch() {
this.config_URL = "";
this.gas_popup_feature_enabled = "";
}


my code fails on field2.set(object2, val);


with this exception



java.lang.IllegalArgumentException: Can not set java.lang.String field com.w.state.ProviderSearch.config_URL to java.lang.String





Best way to compare two objects. Quiz

Im making a new years eve quiz for some friends. The quiz itself is done and working I just thought it would be cool to autocorrect the answers once they are posted.


The question is what's the best way to compare the posted object with an object that has all the right answers, reflection?. There has to be a slick way to do it and avoid having a lot of if's.



public class QuizModel
{
public string Name { get; set; }
public string Quiz1 { get; set; }
public string Quiz2 { get; set; }
public string Quiz3 { get; set; }
etc..
}


You dont have to write me any code. I just want some directions on what the best ( and most important the coolest) way to do it :)






Reflecting on a Type parameter

I am trying to create a function



import Language.Reflection
foo : Type -> TT


I tried it by using the reflect tactic:



foo = proof
{
intro t
reflect t
}


but this reflects on the variable t itself:



*SOQuestion> foo
\t => P Bound (UN "t") (TType (UVar 41)) : Type -> TT





Invoking WebApi's another action in another controller via reflection ?

We have many services in our system. ( integrating with a mobile company)


So, (for example) we have :



Action1 in Controller1
Action2 in Controller1
...

Action4 in Controller4
Action5 in Controller4
...


Currently, the mobile company calls each action with a single request.


But recently they told us , "can we send you a list of Actions to invoke ? instead of running single action manually each time... ?"


So I tried reflection:


ServicesController :



[HttpGet]
[AllowAnonymous]
public HttpResponseMessage AAA( )
{
Type type = typeof(UsersController);

var instance = Activator.CreateInstance(type);

MethodInfo method = type.GetMethod("Test2", BindingFlags.Instance | BindingFlags.Public);
var t= method.Invoke(instance, new object[] { "royi" });

return Request.CreateResponse(HttpStatusCode.OK, t);
}


And :


UseresController :



[HttpGet]
[AllowAnonymous]
public HttpResponseMessage Test2( string ggg)
{
return Request.CreateResponse(HttpStatusCode.OK, "hello"+ggg);
}


When I run via fiddler :


http://es.com/api/services/aaa ( GET)


It does work , but (obviously) the Request on the other side is null :


enter image description here


Question


How can I make Test2 run as expected ? am I on the right direction of solving this ? or does webApi has built in mechanism for this sort of thing ?






lundi 29 décembre 2014

Java: Is it possible to get reference to instantiating object through reflection?

I'd like to get a reference to the object that created this object (i.e. by calling new) through reflection or using a ClassLoader or similar hack? Is there any way to do this? No need to ask why I'd like to do this or offer alternatives because I'm just looking for a yes or no answer. Thanks a lot






Modify a method annotation parameter at runtime

I found this thread: How to change annotation value at runtime using reflection?


And I trying to change method annotation, but java.lang.reflect.Method don't contains any map-field like "annotations" or method like "getDeclaredAnnotationMap"


There is only private byte[] annotations but what can I do with this byte array?


So, how to modify annotation of method?






Implementing a Totals row while keeping concerns separate?

I'm currently working on a C# MVC5 application. I've managed to contain almost all of the Business logic rules to the ViewModel, Model (attributes only), and Store Procedures.


That being said I have a static class that exports an class to CSV (and later other types). This exporter uses Reflection using the DisplayAttribute for Name and Order.


The totals are calculated and stored in the ViewModels, which currently the Exporter doesn't use aside from acquiring the initial list of models. My goal is to append a totals row to the exported file while maintaining a good OOP design. I see two possible paths that I can take:





    1. Send the totals with the initial list of models to the exporter.





    1. Calculate the totals in the exporter using a CustomAttribute to indicate which totals to calculate.




Pros/Cons of Method #1:



  • Doesn't use Reflection

  • Requires the order and spacing of columns for totals row to be known in the ViewModel, which I'm trying to keep that knowledge purely in the Models (attributes).


Pros/Cons of Method #2:



  • Uses Reflection; However the Exporter already uses reflection and it's faster than previous methods and easier to maintain.

  • Some of our totals are just simple sums or counts. For example we have one that is Sum(P1) / (Sum(P2) + Sum(P3)). In this case I was thinking we could make the attribute store the formula using property names (since we're already using reflection) and parse the formula to calculate it. This would require the writing/maintaining of a parser, and might actually increase the time the exporter takes quite a bit.


Question:


Is there a way to add a totals row to my exporter while keeping the following?



  • Totals logic remaining in the ViewModel.

  • Column/Positioning Logic remaining in the Model(attributes).

  • Exporter remaining "generic" (via Reflection).






jpa composite key with embedded field reflection fail

I want to have a primary key with an embedded field, i have managed to have hibernate create the tables, but it is having a problem with saving, when i save (using spring repository), i get the following exceptions:


"org.hibernate.PropertyAccessException: could not get a field value by reflection getter of StockHistory.dateTime"


and down the stack trace there is the exception


"java.lang.IllegalArgumentException: Can not set utils.time.Time field StockHistory.dateTime to utils.time.Time"


this is the primary ID class



public class StockHistoryId3 implements Serializable
{
private static final long serialVersionUID = 1L;

private int stockId;
private Time dateTime;

public StockHistoryId3(){}

public StockHistoryId3(Time time, int stockId)
{
this.setDateTime(time);
this.setStockId(stockId);
}

@Override
public boolean equals(Object target)
{
boolean result = false;

if(target != null && target instanceof StockHistoryId3)
{
StockHistoryId3 other = (StockHistoryId3) target;

if(Integer.compare(this.getStockId(), other.getStockId()) == 0
&& this.getDateTime().equals(other.getDateTime()))
{
result = true;
}
}

return result;
}

@Override
public int hashCode()
{
int result = 89;

result += this.getStockId() + this.getDateTime().getDateTime();

return result;
}

// setters & getters
public int getStockId()
{
return stockId;
}

private void setStockId(int stockId)
{
this.stockId = stockId;
}

public Time getDateTime()
{
return dateTime;
}

public void setDateTime(Time dateTime)
{
this.dateTime = dateTime;
}
}


and this is the class to be mapped (not all of it for brevity)



@Entity
@Table(name = Configuration.DB_TABLE_NAME_STOCK_HISTORY)
@IdClass(StockHistoryId3.class)
public class StockHistory
{
@Id
@Column(name = "stockId", insertable = false, updatable = false)
@JoinColumn(name = "stockId", nullable = false)
private int stockId;

@Id
@Embedded
@AttributeOverrides
({
@AttributeOverride(name="timestamp", column=@Column(name="time")),
})
private Time dateTime;
}


and this is the Time class (not all of it for brevity)



@Embeddable
@Component(value = "Time")
@Scope(value = "prototype")
public class Time implements Serializable
{
private static final long serialVersionUID = 1L;


@Column(name = "timestamp")
private long dateTime;

@Transient
private LocalDateTime date;


public Time(){}

public Time(long timestamp)
{
this.setDateTime(timestamp);
this.setDate(new LocalDateTime(timestamp));
}

@Override
public boolean equals(Object target)
{
boolean result = false;

if(target != null && target instanceof Time)
{
Time other = (Time) target;

if(this.getDateTime() == other.getDateTime())
{
result = true;
}
}

return result;
};
}


any help about my problem thanks






Guava TypeToken in scala

I'm working with a java lib in scala.


I need to impl an abstract class in scala but there's some problem with guava's TypeToken which is used in the abstract class in java. The problem is that sometimes in scala, TypeToken is not able to infer the generic type:



import com.google.common.reflect.TypeToken


class SomeClass[T] {
val tok = new TypeToken[T](getClass){}
}


object TypeTokenTest extends App {
val ok = new SomeClass[String]{}
println(ok.tok) // `java.lang.String`, OK!!

def wrap[O]() = {
new SomeClass[O]{}
}

val notOk = wrap[String]()
println(notOk.tok) // `O`, not Ok ...
}


So in above code, if it's a simple usage, it works very well. But if there's an indirection (the concrete type is passed from the function to the class), it does not work anymore.


Any suggestions on how to make it work?






dimanche 28 décembre 2014

Get the entire assembly in C#

I'm trying to eliminate a call from my API in which the end-user has to pass Assembly.GetExecutingAssembly() in their code, currently my code looks lke the following.



public static Dictionary<int, Packet> Packets { get; private set; }

public static void Init()
{
Assembly assembly = Assembly.GetExecutingAssembly();

foreach (Type type in assembly.GetTypes())
{
if (type.BaseType == typeof(Packet))
{
...
}
}
}


However this only gets all of the classes that are available in the API.dll, and none of the classes from the project that's using the .dll are included,


However if I pass it as a paramter, like so:



public static void Init(Assembly assembly) {}


it loads everything just fine, is this intended behaviour, is there a way to do this all in the background without the end-user ever having to worry about the Assmebly call?


In a nutshell - I have a .dll file that people will be using in their projects, I want to get all of the classes from the project that's using the .dll, not all of the classes inside of the .dll






Compare two objects in Java using reflection and annotations

I have a sample Student object, which has several fields (index number, name, family name, etc.). I'd like to compare two Student objects, but I'd like to define what is the priority of field comparison. For this purpose, I use field annotations, like in the example below:


Annotation interface definition:



@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CompareOrder {
int order();
}


The usage:



@CompareOrder(order = 3)
private int indexNumber;
@CompareOrder(order = 2)
private String name;
@CompareOrder(order = 1)
private String familyName;
private ArrayList <Float> marks;
@CompareOrder(order = 5)
private float average;
@CompareOrder(order = 4)
private boolean fullTime;


Some fields contain no annotation, and are ignored in comparison. The first thing I did, is extracting all fields of the class using reflection and sorting them according to the comparison order, which corresponds to the first part of my compareTo overriden function body:



@Override
public int compareTo(Student other) {
// TODO Auto-generated method stub
Class<? extends Student> clazz = this.getClass();
Field[] fields = clazz.getDeclaredFields();
List <Field> fieldList = new ArrayList<Field> ();
//ommiting unannotated fields
for (Field f : fields)
{
if(f.getAnnotation(CompareOrder.class) != null) fieldList.add(f);
}
//sorting fields by compare order
Collections.sort(fieldList, new Comparator <Field> (){

@Override
public int compare(Field f0, Field f1) {
CompareOrder compOrder0 = f0.getAnnotation(CompareOrder.class);
CompareOrder compOrder1 = f1.getAnnotation(CompareOrder.class);
return compOrder0.order() - compOrder1.order();

}
});

for (Field f : fieldList)
{
// HERE GOES COMPARISON OF OBJECTS FIELD BY FIELD, ACCORDING TO THE ORDERING
}

return 0;
}


And now I'm kind of stuck. Because at this point, I need to decide whether a field of this and other student is greater or smaller. And I can't do that with raw Object type, only thing I can do is call equals method, which is not enough. I need to know if it's greater or smaller. I need to cast it somehow to... yeah, what exactly? How do I extract the field type, and then cast? Is this even doable?


PS. I know, that possibly an easier approach is to use method annotations and invoke getter methods, but I'm just curious whether it is doable the way I'm trying to do it.






samedi 27 décembre 2014

c# Call class Member (property,method,etc) by dymanic name from Other class and method

How can i call and then use (set value) for member of the class, when i do not know class name?


For best understanding let me show example, what i mean:


for example i have class:



static class ClassA {
public static string Property1;
public static bool Property2;
public static async Task<bool> Method () {
// ...
await Worker.Do();
return true;
}
}

static class Worked {
public static async Task<bool> Do() {
// ...
var CallerClassName = new StackTrace().GetFrame(1).GetMethod().ReflectedType.Name;

// setup value for caller class Property 1 = "test";
// Like ClassA.Property1 = "test"; but using dynamic name;
// setup value for caller class Property 2 = true;
// Like ClassA.Property2 = true; but using dynamic name;
}
}


i should say, that i know that those properties exists in Caller class, i do not know how to set up their name dynamicly if i do not know its class caller name. Also i should say that all this methods, property and classes are static.


Thanks for help!






How to call this method when types are known only in runtime?

I'm having troubles invoking this method when the types are unknown at compile time.



public static IObservable<TRet> WhenAnyValue<TSender, TRet>(this TSender This, Expression<Func<TSender, TRet>> property1)


The Expression is typed and method call is also typed.


I thought of using reflection, but the code I get is really tricky and brittle. Is there a good way to "parse" this kind of calls to make them more dynamic?






Creating a property selector Expression from a string

I'm trying to generate a "Property Selector" from a string.


Let me explain myself a bit with a Real life example:


We have a Class Person with a Name (string) property.


I could manually create a "property selector" like this propertySelector writing:



Expression<Func<Person, string>> propertySelector = x => x.Name;


But I would like to get the same property selector with my method.



var propertySelector = CreatePropertySelectorExpression<Person, string>("Name");


What I have so far is this:



public static Expression<Func<TIn, TOut>> CreatePropertySelectorExpression<TIn, TOut>(string path)
{
Expression exp = Expression.Parameter(typeof(TIn), "x");
foreach (var property in path.Split('.'))
{
exp = Expression.PropertyOrField(exp, property);
}
return exp;
}


But... I've got and invalid cast error!



Cannot implicitly convert type 'System.Linq.Expressions.Expression' to 'System.Linq.Expressions.Expression>'. An explicit conversion exists (are you missing a cast?)



I'm very new to Expressions and I don't know how to continue :(






Obtaining ears inside ejb programmatically

There is an ear file deployed under WLS. It contains a lot EJBs.


(My goal I want to be able, using a servlet, access and pull the list of deployed ejbs, and using reflections invoke them)


My question what would be the most simple way to abtain list of ejbs? Should I parse the descriptoe file inside ear?


thanks






vendredi 26 décembre 2014

Reflection IllegalArgumentException java

What i am trying to do: get the value of the a reflected field named "f3" with the type "K". I would like to be able to use the value of f3 to reflect fields from within it.


All methods of getting the value that i try give the error: can not set K field f3 to java.lang.Class.


Question: How can i get the value of "f3" which has the type "K"?


Code that throws IllegalArgumentException:


Field fieldf3 = instance.getDeclaredField("f3"); fieldf3.setAccessible(true); Object value = fieldf3.get(instance); //exception on this line.


exception: java.lang.IllegalArgumentException: Can not set K field b.f3 to java.lang.Class at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58) at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36) at java.lang.reflect.Field.get(Field.java:387)


sorry for poor english






Instantiating various inherited classes through one method, without reflection

In a project I'm working on, I have a set of blocks that make up a 3D voxel based environment (like Minecraft). These worlds are stored in an external data file.


This file contains the data for: Each block, its location, and its type.


When the LoadLevel method is called, I want it to iterate over the data for every block in the file, creating a new instance of the Block object for every one. It's no problem to pass things like location. It's as simple as



CreateBlock(Vector3 position)


The issue is with the type. All types are child classes (think Abstract Block, and then subtypes like GrassBlock or WaterBlock that inherit the abstract Block's properties.) Assuming there's a child class like "GrassBlock" that I want to be created, rather than a generic block, how do I make it do this through the method? The only way I know of is through reflection, which I've been advised to stay away from. Is it possible that I can do this through generic typing or something?


This seems like such an important question in game design, but no one I've asked seems to have any idea. Any help?






Cannot access field to change its modifier using java reflection

What im trying to do is:



Field f = /*some field from some class. the field modifier is "protected"*/
f.setAccessible(true);


But it says I cant access a field with "protected" modifier... So if I cant access it, how will I change the modifier?


Thanks!


EDIT:



((Field) getAllFields(nestedClass).get(1).get(nestedObj)).setAccessible(true); /*Exception is thrown because of this line*/
private ArrayList<Field> getAllFields(Class<?> c) {
ArrayList<Field> fields = new ArrayList<>();
do {
fields.addAll(Arrays.asList(c.getDeclaredFields()));
c = c.getSuperclass();
} while (c != null);
return fields;
}





this is a tricky one for me...

First I'll try to explain my scenario, after that it will become the question, be patience... :-)

I'm developing a kind of compiler, so I have a common interface:



interface Command
{
bool IsValid { get; }
// ... another properties
}


And a base class:



class CommandBase<T>: Command where T : CommandBase<T>, new()
{
public bool IsValid { get; set; }
// ... another properties

public static Command Create<T>()
{
return new T();
}
}


With this layout, it becomes easy to create new command, just creating derivated classes like this:



class Command1 : CommandBase<Command1> { }
class Command2 : CommandBase<Command2> { }
... etc


I have a "Interpreter" class where I have an array like this:



CommandsCache = new Func<Command>[]
{
Command1.Create,
Command2.Create
}


Using this array, is easy to find which commands fits better using LINQ:



var command = CommandsCache
.Where(p => /* some checks */)
.FirstOrDefault(p => p.IsValid);


This way I just ripoff a lot of check codes.


Now it comes my question: How can I do to not need to update my array everytime I create a new "command"?


I just come this far:



var commands = typeof(Command)
.Assembly
.GetTypes()
.Where(p => p.IsClass)
.Where(p => p.BaseType != null && p.BaseType.Name.StartsWith("CommandBase"));


Fine, I got all types that IS a "CommandBase" derivated.

But how to invoke the "Create" saying that "T" is one of "commands"?






jeudi 25 décembre 2014

Reflection Field setValue for inner object


class User{
Account account;
String name;
}

class Account {
Integer amount;
}


**main :**
User u = new User();
Field field = u.getClass().getDeclaredField("account");
field.setAccessible(true);
Field amount = field.getType().getDeclaredField("amount");
amount.set(field, new Integer(1000));


console :



Exception in thread "main" java.lang.IllegalArgumentException: Can not set
java.math.BigDecimal field com.company.Account.amount to java.lang.reflect.Field


How to set value into Account.






RuntimeMethodInfo equality: bug?

Lets start with:



using System;

public class Program
{
class A
{
public virtual void Do() { }
}

class B:A
{
}

public static void Main()
{
var m1 = typeof(A).GetMethod("Do");
var m2 = typeof(B).GetMethod("Do");

Console.WriteLine("Methods are equal?\t\t{0}", m1 == m2);
Console.WriteLine("Method handles are equal?\t{0}", m1.MethodHandle == m2.MethodHandle);

Console.WriteLine("Done.");
Console.ReadKey();
}
}


(try it online at ideone)


So, there are two unequal MethodInfo instances, both containing the same method handle. Here's the equals operator source:



public static bool operator ==(MethodInfo left, MethodInfo right)
{
if (ReferenceEquals(left, right))
return true;

if ((object)left == null || (object)right == null ||
left is RuntimeMethodInfo || right is RuntimeMethodInfo) // <----???
{
return false;
}
return left.Equals(right);
}


It doesn't look like an accidental bug, at least until there was assumption that all instances of RuntimeMethodInfo are cached and there newer will be two different instances for the same method. In that case something is broken, obviously.


Any reasons behind this behavior, anyone?


P.S. Do not mark as a [duplicate], please:) The question is not about 'how to compare?'. That one was answered multiple times, here and here for example.


Thanks!






mercredi 24 décembre 2014

How to walk a C# object hierarchy and create JSON string?

I am creating a metadata site for our API. It is like swagger implementation. Currently I am facing difficulty with creating a sample JSON representation of our request response objects. These are complex objects that may even contain lists.


Right now I am at the point where via using reflection I am able to find all the request and their corresponding response objects.


Is there a library that can convert a reflection



assembly.GetType("FullyQuallifiedObjectName")


output to a JSON sample string? My research so far has not been fruitful.






Is there a way to load classes of a certain package dynamically in android?

I need to load classes from a certain package dynamically.


What I don´t want to do is this:



DexFile df = new DexFile(context.getPackageCodePath());
for (Enumeration<String> it = df.entries(); it.hasMoreElements(); ) {
String s = it.nextElement();
}


As it is too slow if my app contains certain libraries as Google Play services, support lib and so on.


is there a way to load classes from a certain package inside the dexfile without filtering all classes first?






Concatenating package and class names (java reflection)

I have a Package instance and a class name as a string. Is there any elegant way to concatenate them (so I can run Class.forName() on the result)?


I could of course just extract the string from the package and add a period between it and the class name, but there must be a more elegant way to do it.






How to get HTML code of webpage with awesoimum?

This is my best attempt, but it doesn't seem to retrieve the body of html (i get only the head part).



Dim page_source As String = DirectCast((From k In DirectCast(Reflection.Type _
Info.GetTypeFromHandle(WebControl2.GetType.TypeHandle), _
Reflection.TypeInfo).DeclaredMembers Where k.Name = "qnTkKOiivD"). _
First, FieldInfo).GetValue(WebControl1)


"qnTkKOiivD" is the name of the private property that holds what seems to be the pagesource in the WebControl.






JPA: Search for an associated entity in an entity hierarchy

I've a PARENT Entity which has 1-M associations with other child table entities. Those child entities may further have associations with other table entities. In my application we load the PARENT entity and subsequent child entities also get loaded along with it.

Example:



[PARENT]
-X
--X1
--X2
---X2a
-Y
--Y1
--Y1
-Z
--Z1

I am stuck in an implementation where I have to search for a particular child entity object which could be anywhere in PARENT entity's hierarchy; update that child entity and save the Parent object.



E.g.: PARENT > X2 > X2a is to be updated.



Problem is there is no certain level of hierarchy i've to search through. I did try to implement JPA Metamodel and reflection api but couldnt find anything which could help me search for the entity in the loaded PARENT entity.


Can someone guide me to right way?






mardi 23 décembre 2014

Get name of a property and declaring class

How can I use reflection to get the name and declaring class of a property of a generic type.


How can I use reflection to get the name and declaring class of a property of a generic type.


The purpose is to get an exception if I read a property where nothing has been written so far.


One of the problems is that the check must be independent of the declaring class.


value.GetType().DeclaringType is always null.



using System;

namespace TestCodeContract
{

public struct CheckForNull<T> where T : struct
{
private T? backingField;

public static implicit operator T(CheckForNull<T> value)
{
if (!(value.backingField.HasValue))
{
var t1 = value.GetType().DeclaringType; // always null.

var propertyName = "Delta"; // TODO get from Reflection
var className = "ContractClass"; // TODO get from Reflection
var msg = String.Format("Proprety '{0}' in class '{1}' is not initialized", propertyName, className);
throw new ApplicationException(msg);
}
return value.backingField.Value;
}

public static implicit operator CheckForNull<T>(T value)
{
return new CheckForNull<T> { backingField = value };
}
}

public class ContractClass
{
public CheckForNull<int> Delta { get; set; }

public void Test1()
{
int x = Delta; // Wanted: "Property 'Delta' in class 'ContractClass' is not initialized"
}
}
}





How to create an instance of a class which implements a contravariant interface and cast

I have the following:



public interface IWidgetUpdated<in TViewModel> where TViewModel : BaseWidgetViewModel, new()
{
string SystemName { get; }

Widget UpdateFromViewModel(TViewModel viewModel);
}


public abstract class BaseCcWidget<TViewModel> : IWidgetUpdated<TViewModel> where TViewModel : BaseWidgetViewModel, new()
{
public abstract string SystemName { get; }

public virtual Widget UpdateFromViewModel(TViewModel viewModel)
{
var widget = _widgetService.GetById(viewModel.Id) ?? new Widget();
widget.Name = viewModel.DisplayName;
if (widget.Id == 0) //Don't allow changing of widget type as set data might be incompatible.
widget.SystemName = viewModel.SystemName;

return widget;
}
}

public class StaticContentWidgetViewModel : BaseWidgetViewModel
{
//Code removed for brevity
}

public class StaticContentWidget : BaseCcWidget<StaticContentWidgetViewModel>
{
//Do implementations - removed for brevity
}

public IEnumerable<IWidgetUpdated<BaseWidgetViewModel>> GetUpdatableWidgets()
{
var result = new List<IWidgetUpdated<BaseWidgetViewModel>>();

var types = _typeFinder.FindClassesOfType(typeof(IWidgetUpdated<>));
foreach (Type drType in types)
{
var obj = EngineContext.Current.ResolveUnregistered(drType); //Creates an instance of StaticContentWidget
result.Add(obj as IWidgetUpdated<BaseWidgetViewModel>);
}
return result;
}


The issue I have is obj as IWidgetUpdated<BaseWidgetViewModel> doesn't work. I use the same code on covariant interfaces with success but it won't work in this instance.


Basically, I just need to be able to call obj.UpdateFromViewModel(). I've tried various casts without success.






Retrieving all types that implement an interface result differ between Covariant and Coinvariant interfaces

I'm trying to get all types that implement a certain interface but it doesn't work when the Interface is co-invariant.


This is what I'm trying:



public class BaseWidgetViewModel {}
public class Widget {}

public interface IWidgetUpdated<in TViewModel> where TViewModel : BaseWidgetViewModel, new()
{
Widget UpdateFromViewModel(BaseWidgetViewModel viewModel);
}

public abstract class TestBaseCcWidget<TViewModel> : IWidgetUpdated<TViewModel> where TViewModel : BaseWidgetViewModel, new()
{
public abstract Widget UpdateFromViewModel(BaseWidgetViewModel viewModel);
}

void Main()
{
Console.WriteLine(
AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => typeof(IWidgetUpdated<BaseWidgetViewModel>).IsAssignableFrom(p)).ToList().Count()
);

}


This will return 0 but when I change the interface to IWidgetUpdated<out TViewModel> then I get a result of 2.


What am I doing wrong?






accessing array members using reflection

It is possible access array elements using Reflection?


For example if i have the array



array<String^>^ Strings_Array=gcnew array<String^>{"One","Two","Three"};


And the function



Replace_Two(Object^ Strings_Array)
{
Type^ Array_Type=Strings_Array->GetType();

String^ Array_Type_Name=Array_Type->ToString(); //it is "System.ValueType[]"

//make magic to replace "Two" to "Four"

}


It is possible to do without type casting?



array<String^>^ Finction_Strings_Array=(array<String^>^)Strings_Array;


Thank you






Downloading and adding jar files to classpath at runtime without reflection

We have a standalone java-application. This application has lots of functionality, but most customers does only use a small bit of this functionality. We want to distribute the application with just the "normal" minimum of third-party jar-files. In the eclipse project all external jar-files are in the class path. So no reflection is used to instanciate classes. So when a user are going to use a more advanced function, eg taking webcamera pictures, we will then download all the javacv jar files and then somehow add these to the classpath/classloader before calling our class that takes a picture. Is this possible? I allready have a working solution for a very small module that downloads some jar-files on the fly and adds them in a custom classloader, but I then have to painfully instanciate every class and call every method by reflection. Eg:



URLClassLoader loader = new URLClassLoader(urls,w.getClass().getClassLoader());
Class grabberClass = Class.forName("org.bytedeco.javacv.FrameGrabber",true,loader);
Object grabber = grabberClass.getMethod("createDefault", int.class).invoke(null, 0);
grabberClass.getMethod("start", null).invoke(grabber, null);
//And so on...


This is not what we want. All our source code is just fine, and I don't want to obfuscate it by turning it into reflection-calls. But how may I use my old code and still be able to add the jar-files at runtime?






Reflection Mapping in OpenGL ES

I am trying to implement the reflection mapping in OpenGL ES 2.0 for 'sphere'. I have done the skybox. For sphere rendering, the reflection shaders i have used are:


Environment mapping (Sphere) vertex shader::



precision highp float;
uniform mat4 u_mvMatrix; // ModelView Matrix
uniform mat4 u_mvpMatrix; // ModelViewProjection Matrix

attribute vec4 a_position;
attribute vec3 a_envmapNormal;

varying vec3 v_eyecoordEyeReflection;

vec3 v_eyecoordPosition;
vec3 v_eyecoordNormal;

void main()
{
// position and normal in model coordinates
vec4 modelCoordPosition = a_position;
vec3 modelCoordNormal = a_envmapNormal;

// Calculate position in eye space
v_eyecoordPosition = vec3(u_mvMatrix * modelCoordPosition);

// Calculate and normalize eye space normal
vec3 eyecoordNormal = vec3(u_mvMatrix * vec4(modelCoordNormal, 0.0));
v_eyecoordNormal = normalize(eyecoordNormal);
// Calculate reflection vector
v_eyecoordEyeReflection = reflect(v_eyecoordPosition, v_eyecoordNormal);

gl_Position = u_mvpMatrix * a_position;
}


Environment mapping (Sphere) Fragment shader



precision highp float;
uniform lowp samplerCube baseCubeMapTexture;
varying vec3 v_eyecoordEyeReflection;

void main()
{
vec4 environmentColor = textureCube(baseCubeMapTexture, v_eyecoordEyeReflection);
gl_FragColor = environmentColor;
}


But i am not getting any output. what is the error in the shader?






Ruby: How to get the default value of optional proc arguments

Let's say I have a proc/lambda/block/method/etc like so:



2.1.2 :075 > procedure = Proc.new { |a, b=2, *c, &d| 42 }
=> #<Proc:0x000000031fcd10@(irb):75>


I know I can find out the names of the parameters with:



2.1.2 :080 > procedure.parameters
=> [[:opt, :a], [:opt, :b], [:rest, :c], [:block, :d]]


But how do I go about getting the value that a given optional parameter would assume if it is not given?




PS: Yes. I know this has been asked/answered before here, but the previous solution requires the use of the merb gem, which is actually slightly misleading. merb itself depended on the methopara gem (unless you're on JRuby or MRI, which I am not) which itself provided the feature at the time the question was answered.


Sadly, presently, methopara appears to be abandonware. Also, it only ever supported ruby 1.9 (and not even the latest version thereof), so I'm looking for a solution that works for current ruby versions.






How to convert Map to case class (recursively)

How to convert Map with nested Map (with key contains name of nested case clas) to case class.


Assuming we have:



case class OuterClass(fieldName1: String, fieldName2: InnerClass)
case class InnerClass(innerFieldName: Int)


How to convert:



Map("fieldName1" -> "stringValue",
"name" -> "ClassName",
"fieldName2" -> Map(
"innerFieldName" -> "value",
"innerClassName" -> "CaseClassName"))


to the



OuterClass("stringValue", InnerClass("value"))


?






lundi 22 décembre 2014

how to fill a composite object using java reflection?

I have a config file like this:


Provider Search,ConfigURL,http://myUrl


I want to fill this object using reflection



public class MyPrefrences {

public ProviderSearch ProviderSearch;
}



public class ProviderSearch {

public String ConfigURL;

}


here is my code, but I fail to set the composite object:



MyPrefrences myPrefrences = new MyPrefrences();

try {
Field field = myPrefrences.getClass().getDeclaredField(normalizedCategory);
Field field2 = field.getClass().getDeclaredField(normalizedKey);
field2.set(field, val);
} catch (Exception ex) {
throw new RuntimeException(ex);
}


how would you do it


a) if all leaves members are String?


b) if I the leaves can be primitives and non-primitives?






dimanche 21 décembre 2014

How can I get the Type from a DeclerationMirror in Dart

I am iterating over my libraries declarations using mirrors so I can read the meta data on my classes. But I need to get the actual type of the declaration I'm currently on, but I don't see a way to do this in the api docs.



var decs = myLibraryMirror.declarations;
decs.forEach((symbol, dec){
dec.metaData.forEach((metaMirror){
var meta = metaMirror.reflectee;
if(meta is TheTypeImInterestedIn){
// do some stuff with the meta object and the class Type it's declared on
// but how to get the Type of the class that the declaration refers too?
}
});
});





Java Serialization Object Input

I made a mistake that I need to find a way to recover from. I am working on an investigation project that requires a large set of samples. I am out of town for the week so I took some samples and used Serialization save the data so I could use it while I am away. In my rush to make progress I guess I changed the base class of the sample class structure and now I can't read the samples any longer. I can't remember what I changed in the base class.


Is there any way to recover from this. I am going to try using the reflection api. Any suggestions would be helpful.






Scala: Getting a TypeTag on an inner type

I'm trying to get a TypeTag or ClassTag for an inner type to provide a ClassTag to a method with type parameters. Specicfically, I have



trait Baz
trait Foo { type Bar <: Baz }


and I'd like to do something like



import scala.reflect.runtime.universe._
import scala.reflect._
typeTag[Foo#Bar] // or maybe
classTag[Foo#Bar]


but I get a 'no typetag available' error. My ultimate goal is to provide ClassTags to something like this



import scala.reflect.ClassTag
class Doer[A,B]()(implicit ctA:ClassTag[A], ctB:ClassTag[B])
object Fooer extendes Doer[Foo, Foo#Bar]()(classTag[Foo], classTag[Foo#Bar])





Reflection in Java - ClassCastException


import java.lang.reflect.*;


class Start
{
public static void main( String[] argv )
{
String me, klasa;
Object arg;
Method met;

int v=argv.length-1;
int argc =argv.length;

if ( argc == 0 ) {
System.err.println( "err!!!");
return;
}

try
{ while (argc!=0)
{
Class<?> c = Class.forName(argv[v]);
klasa = (String) c.newInstance();

Method[] m = InfoInterface.class.getMethods();

arg = m[2].invoke(c.newInstance());
me = (String) m[1].invoke(c.newInstance());
klasa = (String) m[0].invoke(c.newInstance());

met = klasa.getClass().getMethod(me, String.class);
met.invoke(klasa, arg);
--argc;
}

}
catch ( Exception e ) { System.out.println(e) ; return; }
}
}


I dont know why in this code shows me ClassCastException. I have searched the error since hour and i have no idea what's wrong with it. Help me please!


The classes to program are add via commend line.






java reflection. Can not set java.lang.Long field model.vo.Student.name to java.lang.Class

why the following code:



Field idField = t.getDeclaredField("id");
idField.setAccessible(true);

Long o= (Long)idField.get(t);


has the problem Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field model.vo.Student.name to java.lang.Class


and the id is the Long type






scala override static java method

I am trying to use Webgraph http://ift.tt/1hYBsC4 framework in Scala. Here exists some posibility to customize Loader classes. This customization was made via reflection.


... graphClass = Class.forName( graphClassName ); // graphClassName string name of class graph = (ImmutableGraph)graphClass.getMethod( "load", InputStream.class ).invoke( null, is ); ...


in java "load" is static method of class , but how can i write this method on scala to allow my code work ? I have tried



class MyLoader {
def load(filename:String,progressLoader:ProgressLoader ) = ...
}


or even



object MyLoader {
def load(filename:String,progressLoader:ProgressLoader ) = ...
}


with graphClassName = "MyLoader$"


but without success.






Reflection (Java) - create the class object


class Start
{
public static void main( String[] argv )
{
int argc =argv.length;
if ( argc == 0 ) {
System.err.println( "error");
return;
}

try
{
Class<?> c = Class.forName( argv[argv.length-1] );
//c kowalski = c.newInstance( );
}
catch ( Exception e ) { System.out.println(e) ; return; }
}
}
class Test implements InfoInterface
{
public void display()
{
System.out.println("HI!");
}
static int w;
public int dodawanie (int a, int b)
{
w=a+b;
return w;
}
}


**Hi, My problem is how to create the object of Test class in Start class? The Test class have to be add by commend line. In this program i have to get methods from Test class via object in Start class.


Some advice would be very hopeful. Thanks**