I have Type and I want to get the default value. For example, if Type is class or nullable I should get null. But if it is integer, DateTime. decimal, ... I should get 0. What is the best way of doing this?
mardi 30 novembre 2021
lundi 29 novembre 2021
Java Reflect newInstance() causing a ConcurrentModificationException (CME) resulting in a crash
To sum up my project I'm trying to make an event processor that runs methods from a given list of methods. In order to invoke these methods I need to pass in the newInstance of the method. The method is correctly run, however, right after the whole program crashes with a "ConcurrentModificationException".
@EventHandler
private Listener<EventKeyInput> eventKeyInput = new Listener<>(event ->
{
for(Method m : event.getMethods())
{
try {
m.invoke(m.getDeclaringClass().newInstance(), event);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
One of the methods I wish to call
@EventAnnotation()
public void eventKeyInputeTest(EventKeyInput event)
{
System.out.println("EventKeyInput test!");
}
Please let me know if I need to provide anymore code. Thank you for any help!
Dynamic execution of methods and registration of event handlers with reflection in c#
I have a series of instruments with different implementations that share the same IInstrument interface, the instantation was made in this way:
public async Task<object> CreateInstrumentDriver(dynamic input)
{
IInstrument instrument = ((string)input.Name) switch
{
InstrumentA.DRIVER => new InstrumentADriver(),
InstrumentB.DRIVER => new InstrumentBDriver(),
InstrumentC.DRIVER => new InstrumentCDriver(),
_ => throw new NotSupportedException($"{input.driverName} is not supported"),
};
return new
{
connect = (Func<object, Task<object>>)(
async (dynamic arg) =>
{
var info = new InstrumentConnectionInfo
{
Id = (string)arg.id,
Name = (string)arg.name
};
InstrumentDescriptor descriptor = await instrument.Connect(info);
return descriptor.CovertToJSONObject();
}
),
disconnect = (Func<object, Task<object>>)(
async (dynamic arg) =>
{
await instrument.Disconnect();
return null;
}
),
calibrate = (Func<object, Task<object>>)(
async (dynamic arg) =>
{
return await instrument.Calibrate();
}
),
measure = (Func<object, Task<object>>)(
async (dynamic arg) =>
{
Measurement measurement = await instrument.Measure();
return measurement.CovertToJSONObject();
}
),
status = (Func<object, Task<object>>)(
async (dynamic arg) =>
{
return instrument.ConnectionStatus;
}
),
descriptor = (Func<object, Task<object>>)(
async (dynamic arg) =>
{
return instrument.Descriptor;
}
),
onStatusChanged = (Func<object, Task<object>>)(
async (dynamic arg) =>
{
instrument.OnConnectionChanged += (InstrumentConnectionStatus status) =>
{
((Func<object, Task<object>>)arg.handler)(status);
};
return null;
}
),
onRemoteMeasureRequested = (Func<object, Task<object>>)(
async (dynamic arg) =>
{
instrument.OnRemoteMeasureRequested += () =>
{
((Func<object, Task<object>>)arg.handler)(null);
};
return null;
}
),
onRemoteMeasurementResult = (Func<object, Task<object>>)(
async (dynamic arg) =>
{
instrument.OnRemoteMeasurementResult += (Measurement measurement, InstrumentRemoteMeasurementStatus status, string message) =>
{
((Func<object, Task<object>>)arg.handler)(new { measurement, status, message }.CovertToJSONObject());
};
return null;
}
)
};
}
Now I'm calling the instrument instance with this code and it's OK, the object MyInstance is populated correctly with all methods and events of DeviceA and I can persist it somewhere for future use:
var instrumentInstance = new DeviceLib.Startup();
object MyInstance = await instrumentInstance.CreateInstrumentDriver(new InstrumentConnectionInfo { Name = "DeviceA" });
Now the dumb question, since I've not written the CreateInstrumentDriver method (which I admit I din't fully understood the syntax) but in some way I have to call it from another project (where the dll that contains the methos is linked of course) how I can, (I imagine using Reflection) invoke the various functions (connect, calibrate, measure...) and register the event handlers (onStatusChanged, onRemoteMeasureRequested... ) possibly in a dynamic way so, for example if I have in input a string variable with the value "connect" I can invoke the method "connect" (with its parameters), in brief I need a sort of a dynamic Execute(string command, dynamic params) method and a way for dynamically handling the events generated by the instrument so I can execute some code when they have been triggered
dimanche 28 novembre 2021
Create instance of implementation of generic class based on type of Class
I have the following class layout:
abstract class GenericClass<TArgs> where TArgs : ArgsBaseClass { }
abstract class ArgsBaseClass { }
class RandomArgs : ArgsBaseClass { }
class RandomClass : GenericClass<RandomArgs> { }
Now I want to be able to create an instance of RandomClass
from an instance of RandomArgs
, without knowing that it should be RandomClass
. I.e. somehow I need to derive the fact that RandomClass
implements GenericClass<RandomArgs>
.
I'm able to create an instance of GenericClass<RandomArgs>
using:
void CreateSpecificInstance(ArgsBaseClass args)
{
Type genericType = typeof(GenericClass<>).MakeGenericType(typeof(args));
var genericInstance = Activator.CreateInstance(genericType, typeof(args));
// But then I need help for the following step:
Type specificType = ... // in this case RandomClass, but should be derived from 'args'.
var specificInstance = (specificType)genericInstance;
}
Any help is appreciated.
Getting access to class methods after creating an object using reflection
I get different class names (String) from external source e.g: reflection.Test1, reflection.Test2, reflection.OtherTest etc.
I need change these classes to new Objects so that I can use all the methods of a given object I am trying to create a dedicated method:
public static <T extends Base> T createObject(String nameOfClass) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class<T> clazz = (Class<T>) Class.forName(nameOfClass);
return clazz.getDeclaredConstructor().newInstance();
}
But when I try to use it:
createObject("reflection.Test1").fillTest1(); //I want to use method fillTest1 from Test1.class
or:
createObject("reflection.Test2").fillTest2(); // //I want to use method fillTest1 from Test1.class
i get error in IntelliJ:
Cannot resolve method 'fillTest1' in 'Object'
How to make these methods visible? IntelliJ gives me access only to methods in Base.class: I can't see method in my Test1.class and Test2.class
Main.class:
public class Main {
public static <T extends Base> T createObject(String nameOfClass) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class<T> clazz = (Class<T>) Class.forName(nameOfClass);
return clazz.getDeclaredConstructor().newInstance();
}
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
// ... I get different class names from external source e.g: reflection.Test1, reflection.Test2, reflection.OtherTest etc.
createObject("reflection.Test2").fillTest1(); //error :(
}
}
Test1.class:
package reflection;
public class Test1 extends Base{
private String name;
public void fillTest1(String name){
this.name = name;
}
}
Test2.class:
package reflection;
public class Test2 extends Base{
private String test2;
public void fillTest2(String test2){
this.test2 = test2;
} }
Base Class:
package reflection;
public class Base {
public void setBase(){
System.out.println("Base method");
}
}
samedi 27 novembre 2021
Extension method for string variable to read attribute
I have a class with string constants:
public static class Days
{
[Description("Wow!")]
public const string Mon = "Hi!";
}
I've found that it is possible for enum
to have an extension method to read Description
attribute:
using System.ComponentModel;
public enum Days
{
[Description("Wow!")]
Mon
}
An extension method for enum
:
public static string ToName(this Enum value)
{
var attribute = value.GetAttribute<DescriptionAttribute>();
return attribute == null ? value.ToString() : attribute.Description;
}
And call it like that:
Days.Mon.ToName()
Is it possible to write an extension method for string
to get Wow!
from Description
attribute of Mon
string variable and call extension method for string like that?
string description = Days.Mon.ToName(); // Output: "Wow!"
Kotlin Android reflection get class in runtime
I have a response from the server that returns me different objects and each object has a type. How I can match class in runtime with the type I get from the response? This code for example works but I am trying to get rid of the when statement and make it more dynamic.
JsonParser.parseString(jsonArrayString).asJsonArray
.map { tileJsonObject ->
tileJsonObject as JsonObject
val tile = when (tileJsonObject.get("type").asString) {
Red.TYPE -> Red::class.java
Blue.TYPE -> Blue::class.java
else -> Red::class.java
}
Gson().fromJson(tileJsonObject, tile)
}
}
vendredi 26 novembre 2021
Dynamically casting objects from FieldInfo.GetValue in c#
I'm trying to iterate through all the fields in an instance of a class and extract their name / data. The fields themselves are instances of custom classes for storing data with some specific features I needed. The following works:
foreach (var v in typeof(CentralParams).GetFields())
{
if(v.GetValue(_centralParams).GetType() == typeof(BoolEventProperty))
{
BoolEventProperty prop = (BoolEventProperty) v.GetValue(_centralParams);
print(v.Name + " " + prop.Value);
}
if(v.GetValue(_centralParams).GetType() == typeof(FloatEventProperty))
{
FloatEventProperty prop = (FloatEventProperty) v.GetValue(_centralParams);
print(v.Name + " " + prop.Value);
}
if(v.GetValue(_centralParams).GetType() == typeof(IntEventProperty))
{
IntEventProperty prop = (IntEventProperty) v.GetValue(_centralParams);
print(v.Name + " " + prop.Value);
}
}
However I have to manually check for the type of the object in the field, then cast it to a new instance of that type in order to access the Value member. This is annoying as every time I add a new data type to the CentralParams class I will have to handle it explicitly here.
Is there a way I can dynamically cast it to an empty variable of the correct type?
v.GetValue(_centralParams).GetType()
returns the type I need so seems like it should be possible.
Something along the lines of
var type = v.GetValue(_centralParams).GetType();
var prop = (type)v.GetValue(_centralParams);
Thanks
jeudi 25 novembre 2021
Sneaky Inject variable in class constructor
I'm using typescript for test automation and I have a tons of classes like this:
class Something {
//properties
constructor(page:Page){}
//methods
}
class Account {
//properties
constructor(page:Page, accountNumber: string){}
//methods
}
class Navigation {
//properties
constructor(page:Page, navigation: NavigationStrategy){}
//methods
}
same page:Page
object I should pass to all my constructors e.g
it("some test" async => {
const page = await browser.newPage();
const searchPage = new SearchPage(page);
const account = new Account(page, "2135");
const navigation = new Navigation(page, new LHSNavigation(page));
})
How can I automaticaly inject this page
object to all constructors? For examaple I want to get next result
it("some test" async => {
const page = await browser.newPage();
const pageProvider = new PageProvider(page)
const searchPage = pageProvider.create(SearchPage);
// OR
const account = pageProvider.create(Account)("2135");
// OR maybe
const navigation = pageProvider.create(Navigation, LHSNavigation);
})
//Or maybe without page provider
const navigation = Navigation(LHSNavigation);
And all types should be resolved in compile time
Kotlin reflection on Anonymous object using kotlin-reflect
I am receiving a json object in which there is a property I don't know the name of at compile time.
The name of the property is stored in a variable.
Since the name of the property may vary the JSON is parsed as an Anonymous object.
Is it possible to read the value of the property using reflection using the name stored in the variable ?
I tried with code resembling this: jsonResponse::class.memberProperties.find { it.name == variableName }
with no success.
How to check if a property was assigned with 'DateTime.Now' with reflection?
I need to compare two complex objects. My idea was to write a function that iterates over all properties of the object and the sub-objects and write a combination of the property name, the data type and the value in a string. The function returns the hash of this string.
So if the function returns the same hash for two objects the objects are equal. The function is fine. The problem is, that some properties are assigned with DateTime.Now.
tProduct.Timestamp = DataTime.Now;
tProduct.CreatedAt = DataTime.Now;
So if I call my function the string that is created slightly differs in those values.
Example:
//both objects are equal
var complexObject1 = Generate();
var complexObject2 = Generate();
var hash1 = GetHash(complexObject1); // uses string **xxx25.11.2021 15:11:51xxx** to hash
var hash2 = GetHash(complexObject2); // uses string **xxx25.11.2021 15:11:56xxx** to hash
I want to ignore those values in my function and I think I need reflection for this. The logic I want to implement is: If a property gets the value via DataTime.Now I will ignore it.
Implement a struct-to-csv writer in Go
The following code attempt to implement a generic CSV writer for any simple struct. By "simple", I mean field value of the struct are of standard, simple types (int, string etc).
type (
CSV interface {
Header() []string
String([]string) (string, error)
}
CSVArray []CSV
)
func CSVOutput(w io.Writer, data CSVArray, cols []string) error {
if len(data) == 0 {
return nil
}
_, err := fmt.Fprintln(w, data[0].Header())
if err != nil {
return err
}
for _, d := range data {
str, err := d.String(cols)
if err != nil {
return err
}
_, err = fmt.Fprintln(w, str)
if err != nil {
return err
}
}
return nil
}
The problem is CSVOutput()
does not actually work. e.g.:
var data []Employee //the Employee struct implements CSV interface
CSVOutput(w, data, nil)
Compilation failed: cannot use data (type []Employee) as type CSVArray in argument to CSVOutput
I understand that []CSV is not same as []Employee, as explained here, and many other resources available online.
That said, is it possible to rewrite the CSVOutput()
function by using reflection:
func CSVOutput(w io.Writer, data interfac{}, cols []string) error {
sliceOfIntf = castToSlice(data) //how to do this?
if !implementedCSV(sliceOfIntf[0]) { //and how to do this?
return errors.New("not csv")
}
... ...
}
Getting "java.lang.NoSuchMethodException: cicd.testSet.Login.
I tried to call the method from excel sheet and it is getting failed with NoSuchmethodException eventhough I'm using correct set of constructor parameters and everything
Base Class code
Class<?> classname=Class.forName("cicd.testSet."+excelRead.sheet.getRow(flag).getCell(0).getStringCellValue().trim());
String MethodName=excelRead.sheet.getRow(flag).getCell(2).getStringCellValue().trim(); //Method Name from Excel
try{
Object parameter=null;
try{
parameter=excelRead.sheet.getRow(flag).getCell(3).getStringCellValue();
}catch(Exception e){
parameter=excelRead.sheet.getRow(flag).getCell(3).getRawValue();
}
int parameterCount=0;
if(parameter instanceof String)
parameterCount=Integer.valueOf((String)parameter);
else if(parameter instanceof Double || parameter instanceof Integer)
parameterCount=(int)parameter;
for(Method m: classname.getMethods()) //reading Method names from Functional library
{
if(m.getName().equals(MethodName)) //Compapring Method Name with Excel method name
{
if(m.getParameterCount()==parameterCount) //Comparing paraameter Count from both FL and Excel
{
Class<?> param[]={};
if(parameterCount!=0){
param=new Class[parameterCount]; //Creating an array with class
for(int i=0;i<m.getParameterCount();i++)
{
param[i]=m.getParameterTypes()[i]; //assigning values in to array with parameter type
}
}
Method method=classname.getMethod(MethodName,param);
<--Getting error at this Line--> Constructor<?> con=classname.getConstructor(new Class[]{Object.class,Object.class});
method.invoke(con.newInstance(new Object[]{driver,reports}),ParameterData(parameterCount, flag));
}
}
}
Class which I'm calling to invoke the method
\\Constructor
public Login(RemoteWebDriver driver,Reports report){
this.driver=driver;
this.report=report;
logger=BrowserBase.logManager(BrowserBase.testCaseDesc);
commonFunctions=new CommonFunctions(driver, report);
excelRead=new ExcelRead();
}
public void login_field_verification(){
driver.get("https://google.com");
logger.info("URL Loaded in browser https://google.com");
if(driver.getTitle().contains("Google"))
report.reportStepStatus("pass", "URL loaded successfully");
else
report.reportStepStatus("Fail", "URL not loaded successfully");
}
Error Log
java.lang.NoSuchMethodException: cicd.testSet.Login.<init>(java.lang.Object, java.lang.Object)
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.getConstructor(Class.java:1825)
at cicd.base.BrowserBase.TestCaseExecutor(BrowserBase.java:85)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
I tried to find the root cause and upto my research they way I written is correct, but don't know why it is not creating constructor and saying NoSuchMethodException
mercredi 24 novembre 2021
Java, how to check if one ParameterizedType represents a sub-type of another ParameterizedType?
Given below code snippet, for each field of Pojo class, is there a way to check if the type is an integer list or not? The real problem here is the type argument, since it's quite easy to check if it's a list via instanceof
or isAssignableFrom
.
Lines in main
is what I have found so far, but it does not work for those types with more complex class hierarchy.
Please shed some light here, many thanks.
public class Test {
public static void main(String[] args) throws NoSuchFieldException {
// to check if field f1 is an integer list
Field field = Pojo.class.getField("f1");
if (List.class.isAssignableFrom(field.getType())) {
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
if (pt.getActualTypeArguments()[0].equals(Integer.class)) {
System.out.println("Yes, it's an integer list");
}
}
}
}
public static class Pojo {
public List<Integer> f1;
public ArrayList<Integer> f2;
public C1 f3;
public C2<Integer> f4;
public C3<Integer> f5; // notice, this is not an integer list, it's a string list
public C4<Integer> f6;
public C5<String, Integer> f7;
}
public static class C1 implements List<Integer> {...}
public static class C2<T> implements List<T> {...}
public static class C3<T> implements List<String> {...}
public static class C4<T> implements List<Integer> {...}
public static class C5<T1, T2> implements List<T2> {...}
}
Java, is there a way to know if a method return type is a List
Let's say I have a class,
public class Dummy {
public List<Integer> foo() {...}
public Abc<Integer> bar() {...}
}
For method foo
, I can check the return type using ParameterizedType
. But for method bar
, is there a way to know if Ab<Integer>
is actually a List<Integer>
?
Edit to add some background:
We have dozens of 3rd party pojo classes, we need to extract the field information of thess classes, and create a schema based on it.
For the regular primitive field
, it's straight forward, but in those classes, they also have field with type like List<Integer>
, or ArrayList<Integer>
, or Abc<Integer>
(Abc<T>
may or may not implements List<T>
).
So we need a way to determine if it's a repeated field or not, if it's a repeated one, what is the type argument, is it a Integer or some other things?
Many thanks.
Scala - How to extract Json4s with dynamic case class created with ToolBox
I defined the case class dynamically using Toolbox. And when I do extract of json4s, I get the following exception:
import org.json4s._
import scala.reflect.runtime._
import scala.tools.reflect.ToolBox
implicit val formats = DefaultFormats
val cm = universe.runtimeMirror(getClass.getClassLoader)
val toolBox = cm.mkToolBox()
val parse =
toolBox.parse(
s"""
| case class Person( name:String, age:String)
| scala.reflect.classTag[ Person].runtimeClass
""".stripMargin)
val person = toolBox.compile( parse)().asInstanceOf[Class[_]]
val js = JsonMethods.parse("""{ "name":"Tom","age" : "28"}""")
val jv = js.extract[person.type ] //How do I pass the class type?
**"Exception in thread "main" org.json4s.MappingException: No constructor for type Class, JObject(List((name,JString(Tom)), (age,JString(28))))"**
But after creating a dummy instance of the dynamically created class, Then pass in the type of that dummy class and it will be parsed.
I don't know why. How can I parse without creating a dummy instance?
import org.json4s._
import scala.reflect.runtime._
import scala.tools.reflect.ToolBox
implicit val formats = DefaultFormats
val cm = universe.runtimeMirror(getClass.getClassLoader)
val toolBox = cm.mkToolBox()
val parse =
toolBox.parse(
s"""
| case class Person( name:String, age:String)
| scala.reflect.classTag[ Person].runtimeClass
""".stripMargin)
val person = toolBox.compile( parse)().asInstanceOf[Class[_]]
val dummy = person.getConstructors.head.newInstance( "a", "b") //make dummy instance
val js = JsonMethods.parse("""{ "name":"Tom","age" : "28"}""")
println( js.extract[ dummy.type ] ) // Result: Person(Tom,28)
Cast classes to classes with generics
I am reflectively getting classes and their declared classes, and I want to pass them into a function that takes classes, but it has generics on it.
// classes to pass into function
ClassPath.from(MyParent.class.getClassLoader())
.getTopLevelClasses()
.forEach(classInfo -> {
// checks...
Class<?> clazz = classInfo.load();
for (Class<?> declaredClass : clazz.getDeclaredClasses()) {
genericFunction(clazz, declaredClass); // the problem
}
});
// the function to pass into
<E extends Extendable<? extends Parent<E>>> void genericFunction(Class<? extends Parent<E>> parentClass, Extendable<E> extendableClass);
// classes used in generic function
public class MyParent extends Parent<MyExtendable> {
protected class MyExtendable extends Extendable<MyParent> {
}
}
public abstract class Parent<E extends Extendable<? extends Parent<E>>> {
}
public abstract class Extendable<E extends Parent<? extends Extendable<E>>> {
}
The problem is that I have no idea how to cast or reflective run that genericFunction()
with the Class<?>
objects.
I can assume that the classes that ClassPath
finds are compatible (e.g: they all properly extend Parent
and Extendable
in inner classes.)
I can change my (likely) messy and overcomplicated generics on the function and classes.
mardi 23 novembre 2021
Check specific values of generic properties
Well, I always can hardcode checking properties in order to solve my case but I want to do it using reflection.
My generic type:
public class AnalyzedParameter<T>
{
public T Value { get; set; }
public bool Valid { get; set; }
}
My class:
public class Foo
{
public AnalyzedParameter<int> A { get; set; }
public AnalyzedParameter<string> B { get; set; }
}
I need to check each property that has type AnalyzedParameter
by checking Valid
property inside.
So my method has to be like this:
public bool IsValid()
{
var props = GetType().GetProperties().Where(prop => prop.PropertyType == typeof(AnalyzedParameter<>));
var valid = props.All(p => ((AnalyzedParameter<object>) p.GetValue(this)).Valid);
return valid;
}
But it does not work. Any ideas?
Bad:bsc contract reflection
I cloned a contract that reflects dogecoin after each buying process It work but do not reflect dogecoin after buying Please help
https://bscscan.com/address/0x86b77fcfb4d6da7f09d335da29dcf27997bf42b5#code
Reflection, compile-time type, runtime type, assemblies, and how they fit together
I've been trying to piece together how reflection, compile-time type, runtime type, assemblies, and metadata fit together in C#. My understanding so far is that reflection allows the runtime to introspect upon the compiled code's assembly metadata. This metadata contains information about the methods and types in our program. For example, we get an object's type.
My questions are:
- When we're getting an object's type via reflection, are we getting the runtime type or static type?
- If we're able to get the runtime type from metadata, how is this happening?
- Couldn't I just use "GetType()"?
- And an assembly is compiled code, runtime types aren't known yet, so how can the runtime type be extracted from an assembly's metadata?
As an example:
Base b = new Derived();
Console.WriteLine(b.GetType());
I understand that Derived is logged. But how? If GetType retrieves the type via reflection, which consults the assembly's metadata, how is the runtime type being logged? Doesn't the metadata only contain type information based on compile time?
Just after some clarification, big or small, whatever is necessary. And please correct anything I've said that's incorrect.
lundi 22 novembre 2021
Elixir - Changing default behavior of actors
I am currently looking into the behavioral reflection possibilities of Elixir, a language to which I'm pretty new. Specifically, I am searching for a way to change the default behavior of actors within Elixir, or install hooks within this behavior. As a classic example, let's say I want to log messages when they are send from one actor, arrive in the other actor and are actually processed. Could I change/override/hook into the default behavior of these hypothetical 'send', 'arrive' and 'process' methods in orde to add this functionality as 'default behavior'? How would this be done?
The logging example above is just an example. I am looking to use the approach used to implement this example in a broader context (eg. change default mailbox behavior).
Define a generic lambda in C# and assign it to a variable to be used with MakeGenericMethod
I know I can define a generic function and then call it with Type parameters by help of reflection. Something like that:
private static void SomeFunc<Tf>()
{
// Something type safe against Tf
}
public void CallingFunc()
{
var someType = typeof(whatever); // This may be retrieved using reflection as well instead
var someMethod = this.GetType().GetMethod(nameof(SomeFunc)), BindingFlags.Static | BindingFlags.NonPublic);
var typedMethod = someMethod.MakeGenericMethod(someType);
typedMethod.Invoke(null, null);
}
Now, is there a way to declare this SomeMethod<Td>()
inline as a lambda, to avoid declaring it as a separate method in the class, but still being able to use it with MakeGenericMethod
? Something like:
public void CallingFunc()
{
var someType = typeof(whatever); // This may be retrieved using reflection as well instead
// This obviously doesn't work as it requires Tf to be known at this stage, and we can have Tf only as a Type variable here => what should I do instead?
var someMethod = new Action<Tf>(() => /* Something type safe against Tf */).Method;
var typedMethod = someMethod.MakeGenericMethod(someType);
typedMethod.Invoke(null, null);
}
Making CallingFunc
generic as well is not an option - the someType
variable is retrieved with reflection so is not known on compile time.
dimanche 21 novembre 2021
Call methods from txt file via reflection [duplicate]
I want to read a txt file containing methods and calls them. But I couldn't write this code. In example code can contains dummy prints. I can modify.
Is there anybody has this example?
samedi 20 novembre 2021
PHP Reflection: identify correct constructor
PHP ReflectionClass::getConstructor() gives a class's constructor.
If a child class has no constructor defined but its parent class does, then the parent constructor is returned.
Is there a way to distinguish whether the constructor came from a child class or its parent?
Generate interface implementation with Reflection.Emit for List of given properties
I am using code from this question to generate class from list of property
public class Field
{
public string FieldName;
public Type FieldType;
}
public static class MyTypeBuilder
{
public static Type CompileResultType()
{
TypeBuilder tb = GetTypeBuilder();
ConstructorBuilder constructor = tb.DefineDefaultConstructor(MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
// NOTE: assuming your list contains Field objects with fields FieldName(string) and FieldType(Type)
foreach (var field in yourListOfFields)
CreateProperty(tb, field.FieldName, field.FieldType);
Type objectType = tb.CreateType();
return objectType;
}
private static TypeBuilder GetTypeBuilder()
{
var typeSignature = "MyDynamicType";
var an = new AssemblyName(typeSignature);
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
TypeBuilder tb = moduleBuilder.DefineType(typeSignature,
TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout,
null);
return tb;
}
private static void CreateProperty(TypeBuilder tb, string propertyName, Type propertyType)
{
FieldBuilder fieldBuilder = tb.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);
PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, propertyType, Type.EmptyTypes);
ILGenerator getIl = getPropMthdBldr.GetILGenerator();
getIl.Emit(OpCodes.Ldarg_0);
getIl.Emit(OpCodes.Ldfld, fieldBuilder);
getIl.Emit(OpCodes.Ret);
MethodBuilder setPropMthdBldr =
tb.DefineMethod("set_" + propertyName,
MethodAttributes.Public |
MethodAttributes.SpecialName |
MethodAttributes.HideBySig,
null, new[] { propertyType });
ILGenerator setIl = setPropMthdBldr.GetILGenerator();
Label modifyProperty = setIl.DefineLabel();
Label exitSet = setIl.DefineLabel();
setIl.MarkLabel(modifyProperty);
setIl.Emit(OpCodes.Ldarg_0);
setIl.Emit(OpCodes.Ldarg_1);
setIl.Emit(OpCodes.Stfld, fieldBuilder);
setIl.Emit(OpCodes.Nop);
setIl.MarkLabel(exitSet);
setIl.Emit(OpCodes.Ret);
propertyBuilder.SetGetMethod(getPropMthdBldr);
propertyBuilder.SetSetMethod(setPropMthdBldr);
}
}
and I have interface to get/set it's properties to avoid using reflection and dynamic
public interface IDynamicObject
{
T GetProperty<T>(string propertyName);
void SetProperty(string propertyName, object value);
}
Can anybody help me modify this code to generate a class implementing my IDynamicObject interface so it generate something like this (for example two string properties "Str1" and "Str2")? Sadly am not good with Reflection.Emit yet...
public class TestClass : IDynamicObject
{
public string Str1 { get; set; }
public string Str2 { get; set; }
public T GetProperty<T>(string propertyName)
{
switch (propertyName)
{
case nameof(Str1):
return CastObject<T>(Str1);
case nameof(Str2):
return CastObject<T>(Str2);
default: throw new ArgumentException();
}
}
public void SetProperty(string propertyName, object value)
{
switch (propertyName)
{
case nameof(Str1):
Str1 = (string)value;
break;
case nameof(Str2):
Str2 = (string)value;
break;
default: throw new ArgumentException();
}
}
public T CastObject<T>(object input)
{
return (T)input;
}
}
Is it possible to instantiate a generic type's property through reflection?
I am trying to create an abstract class that initializes T
class properties by iterating a json-style object passed in constructor.
abstract class JSONClass<T> {
// Receive a JSON object implementing all T properties
constructor(json: JSONClassDictionary<T>) {
this.fromJSON(json);
}
fromJSON(json: JSONClassDictionary<T>) {
for (let key in json){
let prop = this[key];
if (prop is not a class) { <// -- 1) Determine whether it's a class
this[key] = prop;
}
else{
const constructor = getConstructorOf(T[key]) // <-- 2) Get constructor of T[Key] property. This is no-sense to compiler
this[key] = new constructor(prop)
}
}
}
}
The problem is that T
may have some properties which are not primitive types, and require initialization.
Example of real case scenario and invocation:
class UserRole extends JSONClass<UserRole> {
id;
name;
permissionGroup: PermissionGroup;
}
const role = UserRole({
id: 1,
name: "Admin",
permissionGroup: {// <-- This will be converted to PermissionGroup() in fromJSON
id: 1,
action: ".."
}
})
This means that when fromJSON
is iterating through the property permissionGroup
, it should not perform this[key] = prop;
but this[key] = new PermissionGroup(prop)
.
I am having issues in Point (1) and Point (2) as shown in code comments, specifically in:
-
Being able to determine whether the key I'm iterating in
json
is an instantiable class property ofT
, instead of a primitive type; -
If true, the initialize property of
T
.
Is this achievable?
How to automatically subscribe to events [closed]
I want to log all events that have a subscriber, without having to write a line with a log in each event.
there is a possibility?
c# Loop 10000 textboxes without writing their name
Example:
I have 1000 textboxes in 1 form. The textboxes names are textbox1, textbox2 ... textbox1000 I want to be able to do the following thing:
String myString = "textbox";
for (int i = 0; i <= 1000; i = i + 1)
myString + i.Text = "Textbox number " + i.ToString()
next
IMPORTANT, solve my goal not my example
My goal is to not write the textbox, and get it from a predefined string, well, like the example
Sorry for the confusion and the edits. Its my first post :/
vendredi 19 novembre 2021
C# Using Reflection to subscribe to Events
I have a program where i am using Reflection to load classes dynamically based on a text file.
When i run my code i can get all the classes, methods and Events printing to screen and can even Invoke the methods.
I added all events to a Dictionary and i want to enumerate through them and then create a Event Handler to get the data sent by the event.
here is my method for getting the events to a dictionary:
private Dictionary<string, EventInfo> RetrieveEvents(string label, string type)
{
try
{
this.displaysAssembly = Assembly.LoadFrom(Path.Combine(Directory.GetApplicationDirectory(), "Framework.DisplayDrivers.dll"));
string assembly = string.Format("Framework.DisplayDrivers.{0}", type);
Type cswitcher = displaysAssembly.GetType(assembly);
fullClass = cswitcher;
Dictionary<string, EventInfo> ekvp = new Dictionary<string, EventInfo>();
List<EventInfo> eventInfos = cswitcher.GetEvents().Where(e => HasInformationAttribute(e)).ToList();
foreach (var e in eventInfos)
{
if (!ekvp.ContainsKey(label))
{
ekvp.Add(e.Name, e);
}
}
return (ekvp);
}
catch (MissingMethodException e)
{
ErrorLog.Error(LogHeader + "Unable to create Display. No constructor: {0}", e.Message);
}
catch (ArgumentException e)
{
ErrorLog.Error(LogHeader + "Unable to create Display. No type: {0}", e.Message);
}
catch (NullReferenceException e)
{
ErrorLog.Error(LogHeader + "Unable to create Display. No match: {0}", e.Message);
}
return null;
}
if I print out the Dictionary i can see the events by Key and Value.
but i cannot seem to create an Event handler. I have tried many options including:
foreach(var evnt in d._projectors._events)
{
EventInfo ev = evnt.Value;
try
{
// this id not work
object classInstance = Activator.CreateInstance(d._projectors.fullClass);
ev.AddEventHandler(classInstance, new EventHandler(DisplayChangeEvents.DisplayMuteChangedEvent));
// this did not work either
if (d._projectors._events.TryGetValue("OnPowerStateRecieved", out ev))
{
ev.AddEventHandler(ev.Name, new EventHandler(DisplayChangeEvents.DisplayPowerChangedEvent));
}
}
catch (Exception ex)
{
ErrorLog.Error("Error creating event handers : " + ex.Message + "\r");
}
}
i am trying to subscibe to the event and handle the data in another class named "DisplayChangeEvents".
i have been trying for 2 days to get this and its the last piece i need to get the program working as expected.
Thanks in advance
How do I Dynamically set properties from the name in a parent class?
How do I dynamically set the "Name" properties of each of the AlarmModel's as the name of the model (i.e. HardwareFault) from the parent class?
public class NotificationModel
{
public string UnrelatedProperty { get; set; } // any solution should ignore other properties.
public AlarmModel HardwareFault{ get; set; }
public AlarmModel TimeoutFault { get; set; }
public AlarmModel GenericFault { get; set; }
}
public class AlarmModel
{
public string Name { get; set; }
public bool isActive { get; set; }
public bool isEnabled { get; set; }
public bool isSilenced { get; set; }
}
How can I create list of nested classes where a certain property of each nested class is true?
If I have a Model with nested models inside. How can I set the name property based on the NotificationModel and return a list, which is based on properties within the nested model?
I presume using Linq and Reflection.
So I have something like like: (Assume the alarms are initialised and whether they are enabled or not from a database).
public class AlarmController : IAlarmController
{
public AlarmController()
{
this.NotificationModel = new NotificationModel();
}
public NotificationModel NotificationModel { get; set; }
public List<AlarmModel> GetAlarmModels()
{
//this.NotificationModel --something... where isEnabled == true.
return new List<AlarmModel>();
}
}
public class NotificationModel
{
public AlarmModel HardwareFault{ get; set; }
public AlarmModel TimeoutFault { get; set; }
public AlarmModel GenericFault { get; set; }
}
public class AlarmModel
{
public string Name { get; set; }
public bool isActive { get; set; }
public bool isEnabled { get; set; }
public bool isSilenced { get; set; }
}
I have had a bit of a go at reflection, but haven't found an example like mine. I haven't posted as I think it will confuse the issue. If this isn't the right approach, then please say so.
jeudi 18 novembre 2021
Kotlin generic type extension with reflect
fun <T: Any, R> T.convertTo(r : KCallable<R>) : R {
val that = this
with(r) {
val propertiesByName = that::class.memberProperties.associateBy { it.name }
callBy(parameters.associate { parameter ->
parameter to propertiesByName[parameter.name]?.get(that)
})
}
}
I want to write a generic converter function to convert an object to another, the code like as above. Compiling with error for this line parameter to propertiesByName[parameter.name]?.get(that)
Type mismatch.
Required: Nothing
Found: T
How to solve this problem?
Using reflection to retreive a specific element in an array
Lets say I have an array of Addresses
How can I filter addresses based on given string. Example if a property path has Addresss.First()
, I want it to display the first element, or Address.Last()
the last element.
ex:
var _propertyInfo = case.MainContact.GetType().GetProperty("Addresses");
XPCollection<BillingUnitContactAddress> buAddresses = (XPCollection<BillingUnitContactAddress>)_propertyInfo.GetValue(case.MainContact);
BillingUnitContactAddress buAddress = buAddresses.First(); //dont want to hardcode this
Kotlin - Get static functions with reflection
I was using this piece of code to map all static functions of a Java class to stuff:
fun staticsFromClass(clazz: Class<*>): List<Something> = clazz.methods
.filter { method -> Modifier.isStatic(method.modifiers) }
.map { method ->
//something
}
but I found out it only works on Java code. It filters out companion object functions and singleton object functions. How can I fix it?
Using reflection to trim all strings on an object
Say I have a simple model structure like below and I want to trim the whitespace off of each string in the nested model (Request
which contains a Friend
)
{
public string id { get; set; }
public string name { get; set; }
}
public class Request
{
public string name{ get; set; }
public string street { get; set; }
public List<string> tags { get; set; }
public Friend friend { get; set; }
public string greeting { get; set; }
public string favoriteFruit { get; set; }
}
This implementation only handles the strings on the top Request
level - I need to be able to handle the Friend
level (nested) strings as well.
private static T TrimWhiteSpaceOnRequest<T>(T obj)
{
if (obj != null)
{
PropertyInfo[] properties = obj!.GetType().GetProperties();
foreach (PropertyInfo property in properties) {
try
{
if (property.PropertyType == typeof(string))
{
var o = property.GetValue(obj, null) ?? "";
string s = (string)o;
property.SetValue(obj, s.Trim());
}
else
{
//handle nested Friend object here
}
}
catch (Exception)
{
log.info("Error converting field " + field.getName());
}
}
}
return obj;
}
What can I put in the else to reach the nested layer?
Calling function by string name in activity
I trying to call function by names as string:
Method method = null;
try {
method =
Class.forName("com.lab.android.TabActivity").getMethod(item,String.class);
method.invoke(this, null);
} catch (NoSuchMethodException e) {
Log.e("DTAG","NoSuchMethodException "+e.getMessage());
e.printStackTrace();
} catch (ClassNotFoundException e) {
Log.e("DTAG","ClassNotFoundException "+e.getMessage());
e.printStackTrace();
} catch (IllegalAccessException e) {
Log.e("DTAG","IllegalAccessException "+e.getMessage());
e.printStackTrace();
} catch (InvocationTargetException e) {
Log.e("DTAG","InvocationTargetException "+e.getMessage());
e.printStackTrace();
}
I get an exeptioon:
NoSuchMethodException com.lab.android.TabActivity.somesome [class java.lang.String]
This is the function in my ativity:
public static void somesome() {
Log.d("DTAG","Great Success");
}
mercredi 17 novembre 2021
Return specific type in generic method depending on enum value without Reflection or dynamic during runtime
I have a non-generic IList
which i would like to cast depending on an enum
value during runtime.
I can not change the type of the non-generic IList in the implementation, because it is library code.
Also i do not want to use Reflection (because it is slow) or the dynamic keyword (because it is unsafe and could lead to mistakes down the road).
In the Library Code there is following class:
public class ListView //THIS IS LIBRARY CODE AND CAN NOT BE CHANGED
{
public IList itemsSource { get; set; }
}
Then in my CustomListView class which inherits from ListView i want to cast the itemsSource to the appropiate class depending on ItemType.
Another limitation is that CustomListView can not be generic (dictated by the library we use)
public class CustomListView : ListView
{
public dynamic GetItems()
{
switch (ItemType)
{
case ItemType.A:
return itemsSource.Cast<A>().ToList();
case ItemType.B:
return itemsSource.Cast<B>().ToList();
default:
throw new InvalidOperationException("Not supported");
}
}
}
But i want it to directly return the correct type instead of using dynamic.
Something like (the code below does not work!):
public IList<T> GetItems(ItemType itemType) //The type of T should change depending on what i return
{
switch (ItemType)
{
case ItemType.A:
return itemsSource.Cast<A>().ToList();
case ItemType.B:
return itemsSource.Cast<B>().ToList();
default:
throw new InvalidOperationException("Not supported");
}
}
How would i implement that?
C# - How to use Select LINQ method using properties from a given strings array
Suppose we have a simple class called Person
with properties as FirstName, LastName, Age
.
Now I have a list of properties as a list of strings.
var props = new List<string> { "FirstName", "Age"}.
Now I have a List
of Person
objects.
var persons = new List<Person> {....}
How to use Select
LINQ method to get just the Person properties that appear in the props
?
var result = persons.Select(p => code here)
The result should be a list of anonymous objects, where a anonymous list's item should contain the properties from props
list.
I can't get the attribute name of an abstract class in c#
This is the class:
public abstract class DbAttributeInstance
{
public static DbAttribute AALLAN;
public static DbAttribute AANGXZ;
public static DbAttribute AANGYZ;
public static DbAttribute ABLE;
public static DbAttribute ABOP;
...
}
I used the following code to get the member name, but got nothing:
System.Reflection.PropertyInfo[] properties = typeof(DbAttributeInstance).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
The final purpose of this operation is to test the class DbAttributeInstance
's every attributes' validity, like this:
if (elem.IsAttributeValid(DbAttributeInstance.GEOM)) then...
but there are too many attributes in DbAttributeInstance
so I can't test them one by one. I want to test every member by using the following form:
//original way to be replaced
elem.IsAttributeValid(DbAttributeInstance.member1)
elem.IsAttributeValid(DbAttributeInstance.member1)
elem.IsAttributeValid(DbAttributeInstance.member1)
elem.IsAttributeValid(DbAttributeInstance.member1)
elem.IsAttributeValid(DbAttributeInstance.member1)
...
//new
foreach (member in DbAttributeInstance's members) {
elem.IsAttributeValid(member)
}
mardi 16 novembre 2021
C# modify variables of same type, based on its' current value
So i have a domain class that should handle some notifications config and types for a proxy of all notifications kinds(email, push, sms ...).
This class have some field of a specific type that i called NotificationConfig this type have a status that indicate if the user set this notification type as On or Off on his app, and a enumeration that indicates it's type (1 = mobilePusj, 2 = email, ...).
So my class has a couple of properties of this type, like one for email, and one for mobile push.
I'm trying to build a method capable of changing the status on one of this properties looking to its enumeration type, but not using the property itself. I guess it's some sort of reflection, but i don't really know how can i make it
this is my class:
public class UserNotification : Entity, IAggregateRoot
{
private string _mobileNotificationId;
private NotificationConfig _mobileNotificationConfig;
public NotificationConfig MobileNotificationConfig => _mobileNotificationConfig;
private NotificationConfig _emailNotificationConfig;
public NotificationConfig emailNotificationConfig => _emailNotificationConfig;
public UserNotification(string mobileNotificationId, int notificationSendTypeId)
{
_mobileNotificationId = mobileNotificationId;
// start NotificationConfig via its own constructor
}
}
and i would like to make a method something like this
public void ChangeStatusByType(int notificationTypeId)
{
var rightConfig = GetTheRightPropOfConfigBasedOnTypeId();
rightConfig.SetStatusToOff();
}
This is just an idea that i would like to do since this class could need to acceppt much more notification types, just right it's only two, and as it's grow woudl make really hard to change handly every tipy of notification instance.
C#: Looping through member objects of nested structs
Hi all you c# wizards!
I need to store all the memory offset values of (packed) nested structs within these respective structs. Recusively looping through all the members works fine so far. Also, i get the appropriate memory offset values. This struct contraption might contain several dozends of structs, and several hundreds of other members in the end. But i do this whole thing at initialization time, so CPU performance won't be an issue here.
But:
In this iteration process, it seems i have trouble accessing the actual instances of those structs. As it turns out, when i try to store these offset values, they don't end up where i need them (of course, i need them in the instance "SomeStruct1" and its containing other struct instances, but the debugger clearly shows me the init values (-1)).
I suspect "field_info.GetValue" or "obj_type.InvokeMember" is not the proper thing to get the object reference? Is there any other way to loop through nested struct instances?
Please help! I've desperately debugged and googled for three days, but i'm so out of ideas now...
Thanks for your efforts!
-Albert
This is a simplified example that should compile and execute (WinForms, c#7.3):
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace CodingExample
{
public interface Interf
{
Int32 Offset {get; set; }
}
[StructLayout (LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct sSomeStruct2 : Interf
{
public sSomeStruct2 (bool dummy)
{
Offset = -1;
SomeMember3 = 0;
}
public Int32 Offset {get; set; }
public Int32 SomeMember3;
// much more various-typed members (e. g. nested structs)...
}
[StructLayout (LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)]
public struct sSomeStruct1 : Interf
{
public sSomeStruct1 (bool dummy)
{
Offset = -1;
SomeMember1 = 0;
SomeStruct2 = new sSomeStruct2 (true);
SomeMember2 = 0;
}
public Int32 Offset {get; set; }
public Int32 SomeMember1;
public sSomeStruct2 SomeStruct2;
public Int16 SomeMember2;
// much more various-typed members...
}
public partial class Form1 : Form
{
void InitializeOffsets (object obj)
{
Console.WriteLine ("obj: {0}", obj);
Type obj_type = obj.GetType ();
foreach (FieldInfo field_info in obj_type.GetFields ())
{
string field_name = field_info.Name;
Int32 offset = (Int32) Marshal.OffsetOf (obj_type, field_name);
Type field_type = field_info.FieldType;
bool is_leafe = field_type.IsPrimitive;
// none of theses three options seem to give me the right reference:
// object node_obj = field_info.GetValue (obj);
// object node_obj = field_info.GetValue (null);
object node_obj = obj_type.InvokeMember (field_name, BindingFlags.GetField, null, obj, null);
Console.WriteLine ("field: {0}; field_type: {1}; is_leafe: {2}; offset: {3}", field_name, field_type, is_leafe, offset);
if (! is_leafe)
{
// this writes not as expected:
(node_obj as Interf).Offset = offset;
InitializeOffsets (node_obj);
}
}
}
sSomeStruct1 SomeStruct1;
public Form1 ()
{
InitializeComponent ();
SomeStruct1 = new sSomeStruct1 (true);
InitializeOffsets (SomeStruct1);
}
}
}
Sends Keys in Selenium and getting rid of the Switch
I am sending Keys in the following manner:
switch (keyName)
{
case "Return":
new Actions(WebDriver).SendKeys(Keys.Return).Perform();
break;
case "F4":
new Actions(WebDriver).SendKeys(Keys.F4).Perform();
break;
defult:
"TBD"
}
I would like to get rid of the Switch/Case statement using something like MethodInfo or FieldInfo, But I can't seem to find the right way to do it.
Hopefully you can help...
Thanks
How to register all Hosted Services with reflection in dotnet 5.0
I'm trying to register all my worker services as Hosted service in dotnet 5.0 with reflection.
I've already registered all my project's application services in this way :
private static void RegisterApplicationServices(IServiceCollection services)
{
var applicationServices = (Assembly.GetAssembly(typeof(ConfigurationService)))
.GetTypes()
.Where(x => !x.IsInterface &&
x.GetInterface(typeof(IApplicationService).Name) != null);
foreach (var serviceType in applicationServices)
{
var type = serviceType.UnderlyingSystemType;
services.AddTransient(type.GetInterface($"I{type.Name}"), type);
}
}
But when it comes to Hosted service it doesn't work. I need some way to register all workers as Hosted services.
services.AddHostedService<WokrerService1>();
services.AddHostedService<WokrerService2>();
services.AddHostedService<WokrerService3>();
services.AddHostedService<WokrerService4>();
services.AddHostedService<WokrerService5>();
services.AddHostedService<WokrerService6>();
private static void RegisterHostedServices(IServiceCollection services)
{
//What should I do here?
}
All the workers inherit from a BaseWorker class
public abstract class BaseWorkerService<TWorkerService> :
BackgroundService, IAppHostedService where TWorkerService : class
{
}
public class TransactionSubscriberService :
BaseWorkerService<TransactionSubscriberService>
{
}
I appreciate any help.
Java Reflection to handle the dynamic object mapping of object we got from parsing xml to pojo
I have a scenario where I need to handle xml data that will parsed into object. Requirement is to dynamically map those variables. For example suppose I have an xml :
<request>
<member>
<id>abc</id>
<details>
<ssn>19</ssn>
<verification>
<indicator>Y</indicator>
<fedInd>N</fedInd>
<status>XY</status>
</verification>
</details>
<taxStatus>
<LastYrStatus>NFT</LastYrStatus>
<ThisYrStatus>MFT</ThisYrStatus>
</taxStatus>
</member>
</request>
Now looking at the xml I want to map the field indicator whose exact path is : request|member|details|verification|indicator the dynamic mapping should give me the getter of these variables from respective java object like getRequest().getMember().getDetails().getVerification().getIndicator()
so that if in future path of xml tag got change I don't have to make so many changes in the code it will be dynamically mapped with the new tag location. Can anyone reply how to handle this situation using java reflection or through any other way.
dimanche 14 novembre 2021
Harmony Patch Sealed Class
I'm trying to patch a class that is in a class of its own. The inner class is marked as sealed.
My Code is:
[HarmonyPatch(typeof(RoomManager.HGEAPFPDOEC))]
[HarmonyPostfix]
[HarmonyPatch("_JoinRoomContinuation_b__0")]
static void _JoinRoomContinuation_b__0()
{
}
But after that my process doesn't start anymore.
The inner class -> public sealed class LIIAANCEOMA is declared in -> public class RoomManager
How can I patch that?
How to invoke a java method without knowing parameter types using reflection in java
I'm trying to execute this string in java using reflection
String methodCall = "com.mypackage.util.MathUtil.myFunction(4,\"abc\")";
This code does the job for me (after little string parsing)
Class.forName("com.mypackage.util.MathUtil").getDeclaredMethod("myFunction", int.class, String.class).invoke(null, 4, "abc");
The problem with the above solution is that i need to know the parameter types before invoking the method, and unfortunately i don't have them.
As a solution i can get all declared methods using Class.forName("com.mypackage.util.MathUtil").getDeclaredMethods()
, iterate, match name and parameter count, and manually check types with some logic to identify the appropriate method.
Can java do this heavy lifting for me with something like this
Class.forName("com.mypackage.util.MathUtil").getDeclaredMethod("myFunction").invoke(null, 4, "abc");
This code should try to match the appropriate method and can throw NoSuchMethodException or Ambiguity error when 2 or more similar methods matched. Also feel free to suggest other ways to achieve this use case.
extract action input parameters from model in .net using reflction
I have this controller
public class AccountController : BaseController
{
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult> Authenticate(LoginUser model)
{
}
}
And here is my input model
public class LoginUser
{
public string UserName { get; set; }
public string Password { get; set; }
public string CaptchaCode { get; set; }
}
I want to use reflection to extract data .The example of data that I need this output
**Account:Authenticate:UserName ,Password ,CaptchaCode**
I find a code as you can see here :
Assembly asm = Assembly.GetAssembly(typeof(Club.Web.MvcApplication));
var controlleractionlist = asm.GetTypes()
.Where(type => typeof(System.Web.Mvc.Controller).IsAssignableFrom(type))
.SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
.Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any())
.Select(x => new { Controller = x.DeclaringType.Name, input = String.Join(",", x.GetParameters().Select(a => a.Name+"|"+a.ParameterType).ToArray()), Action = x.Name, ReturnType = x.ReturnType.Name, Attributes = String.Join(",", x.GetCustomAttributes().Select(a => a.GetType().Name.Replace("Attribute", ""))) })
.OrderBy(x => x.Controller).ThenBy(x => x.Action).ToList();
But it returns
**Account:Authenticate:LoginUser**
But I need the item of my class
Method GetCustomAttribute returns null, while on local debug it returns a value
I have a code that loads an assembly and categorize data by attributes.
I'm trying to get the actual CustomAttribute object. during debug locally the code returns a value (code compiles to .Net5 and net48)
but during runtime on a remote machine on (.Net5 target) the code returns null when i call GetCustomAttributes.
The Attribute:
[AttributeUsage(AttributeTargets.Interface)]
public class ApiInterfaceDescriptorAttribute : Attribute
{
public string ApiUsageName { get; }
public ApiInterfaceDescriptorAttribute(string apiUsageName)
{
ApiUsageName = apiUsageName;
}
}
Sample interface
[ApiInterfaceDescriptor("powercontrol")]
public interface IMyInterface
{
[ApiMethodDescriptor(ApiExposureLevel.Basic, "a-method...")]
void SomeMethod();
}
The trial to get the attribute
public class ApiDetector
{
private Dictionary<Type, List<MethodInfo>> _apiDictionary = new Dictionary<Type, List<MethodInfo>>();
public void LoadApiElements()
{
var apiKeyDesriptor = key.GetCustomAttribute(typeof(ApiInterfaceDescriptorAttribute)) as ApiInterfaceDescriptorAttribute;
_apiDetector.Add(new ApiDataObjectDescriptor { Name = key.Name, ApiUsageName = apiKeyDesriptor?.ApiUsageName, Type = key });
}
}
when i ran this code locally i get the instance:
Running the code on .Net5 remote machine returns null:
Any help will be welcome. Thanks ahead!
vendredi 12 novembre 2021
Java reflection - get getter method with different name
Is there any way I can get the getter
method of a field, which is having different name from the usual standards?
class Employee {
private String name;
private String dept;
public String getTheName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTheDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
}
I know using reflection we can get the getter
method of a field if the getter
method is following the usual standard. Example:
- name ==> getName
- dept ==> getDept
But in our project, we are having a different convention than usual.
Thanks in advance.
JavaReflection generateUMLInfo method
Can someone help me with this please?
generateUMLInfo which takes one parameter of type Object and prints the UML information of the parameter’s class as follows: Each field in fields_list has the format: (vis attribute : type) where vis denotes visibility: ‘-‘ for private, ‘+’ for public, ‘#’ for protected, and ‘*’ for package-friendly. Each method in methods_list has the format: (vis method_name(argument list) : return type) For example, represent the UML information of a Student class
java.lang.reflect.GenericSignatureFormatError for CompletableFuture after Java update to 17 version
I have updated the Java version of our company application from 8 to 17. On local machine it works fine, both in building and on run-time calls. Also on GitHub it is deployed fine, along with the Junit test execution.
The problem is after I deploy the application on Heroku. The Heroku build is on success, but on runtime, when I call the methods, I receive this error:
"message": "Handler dispatch failed; nested exception is java.lang.reflect.GenericSignatureFormatError: Signature Parse error: expected a class type\n\tRemaining input: java/util/concurrent/CompletableFuture",
It's something related to java reflection methods and the method's signature. My controller rest method return a CompletableFuture Object. Something is not good with the CompletableFuture.........
jeudi 11 novembre 2021
How to call a private method using reflection
I am trying to call a private method using reflection. This is what I have tried:
private void CallMethod(string MethodName, object[] Arguments)
{
System.Reflection.Assembly.GetExecutingAssembly().GetTypes().First(x => x.Name == "Form1").GetMethod(MethodName, System.Reflection.BindingFlags.NonPublic).Invoke(null, Arguments);
}
private void Method1()
{
//Code...
}
And when I call CallMethod like this:
CallMethod("Method1", null);
It throws a NullReferenceException. I can a solve this problem? Thanks for any help.
Kotlin: get members of a data class by reflection in the order they have been defined
Assume the following simple example data class:
data class SomeDataClass(
var id: String,
var name: String,
var deleted: String
)
With the following code it is possible to get the properties (and set or get their values):
import kotlin.reflect.full.memberProperties
val properties = SomeDataClass::class.memberProperties
print(properties.map { it.name }) // prints: [deleted, id, name]
The map within the print statement will return a List with the name of the properties in alphabetical order. I need the list in the order they have been defined in the source code, in this case: [id, name, deleted].
It doesn't seem achievable purely through reflection. The only solution I could come up with is to use a helper class defining the order:
val SomeDataClass_Order = listOf("id", "name", "deleted")
This wouldn't be a problem for one or two classes, but it is for hundreds of data classes with the largest one having up to almost one hundred properties.
Any idea would be welcome. I do not need detailed code, rather hints (like parsing the source code, annotations, etc).
java ModuleLayer : ModuleLayer.Controller add methods don't work
I am using Netbeans 12.5 and java 16
In an Java Modular Project I have 2 Modules
Modular-Testing(/*The Project Name*/)
|
|----Consumer(/*Module Name*/)
| |
|--classes(/*Folder Name*/)
|
|--main(/*package name*/)
|
|--CustomModuleTest.java(Main Class)
|--Test_Module_A(/*Module Name*/)
|
|--classes(/*Folder Name*/)
|
|--package_a(/*package name*/)
|
|--ClassA.java
CustomModuleTest.java
public static void main(String[] args)throws Exception
{
Path baseDir=Path.of("C:/Users/Home/Documents/NetBeansProjects/Netbeans/Modular-Testing/build/modules/");
//Create the configuration for these two modules with boot-layer configuration as it's parent
Configuration level1=Configuration.resolve
(
ModuleFinder.of(baseDir.resolve("Consumer"),baseDir.resolve("Test_Module_A"))
,List.of(ModuleLayer.boot().configuration())
,ModuleFinder.of()
,List.of("Consumer","Test_Module_A")
);
//create the module layer with only one system class loader and boot layer as parent
ModuleLayer.Controller layer1=ModuleLayer.defineModulesWithOneLoader
(
level1
,List.of(ModuleLayer.boot())
,ClassLoader.getSystemClassLoader()
);
//this is the main purpose of this test. I want to call ClassA.callMe() via reflection after i have dynamically acheived the permissions for it by first
//Making Consumer Module read(requires) Test_Module_A
//Making Test_Module_A open it's package(package_a) to Consumer
//With this consumer should have full reflective access to Test_Module_A(or that's what i had hoped but it didn't work)
//Require(Read)
//Make Module Consumer--------------->Test_Module_A
layer1.addReads
(
layer1.layer().findModule("Consumer").get()
,layer1.layer().findModule("Test_Module_A").get()
);
//Open package_a
//Make Module Test_Module_A-------------------->Consumer
layer1.addOpens
(
layer1.layer().findModule("Test_Module_A").get()
,"package_a"
,layer1.layer().findModule("Consumer").get()
);
//Do the actual Test
Class targetClass=layer1.layer().findLoader("Test_Module_A").loadClass("package_a.ClassA");
Method method=targetClass.getDeclaredMethod("callMe");
method.trySetAccessible();
method.invoke(null); //<---------Crashes Here(It's a static method so no object reference)
}
ClassA does nothing
package package_a;
public class ClassA
{
private static void callMe()
{
System.out.println("Hooray You Called Me Using ModuleLayers!!!");
}
}
module-info for both Consumer & Test_Module_A are empty
module Consumer{}
module Test_Module_A{}
the module-info of both these modules are empty because i want to dynamically add Opens/Exports using ModuleLayer.Controller
The class is located with no problems the method is made accessable using trySetAccessible() but as soon as i call invoke i get this error
Exception in thread "main" java.lang.IllegalAccessException: class main.CustomModuleTest (in module Consumer) cannot access class package_a.ClassA (in module Test_Module_A) because module Test_Module_A does not export package_a to module Consumer
at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:385)
at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:687)
at java.base/java.lang.reflect.Method.invoke(Method.java:559)
The test is run from CustomModuleTest.java main method inside Consumer Module the addReads & addOpens method either don't work or i am just using it wrong
Any ideas?
Cannot load a certain assembly due to version conflict
One assembly (exe) depends on a nuget package (actually serilog.settings.configuration 3.1.0) This package depends on microsoft.extensions.options.configurationextensions (>=2.0.0) which in turn depends on microsoft.extensions.configuration.binder (>= 2.0.0) All this is ok.
However I have other projects (class libraries) in the solutions which are not referred to from the exe project (to be loaded at runtime) and one of these depends on a newer version of microsoft.extensions.configuration.binder (6.0.0) all is not ok. The new version cannot be loaded because the exe project has already loaded the old one.
I can solve this problem by explicitly add microsoft.extensions.configuration.binder (6.0.0) as dependency for the exe project, but I guess there is a better way to do this, is it? (If the dynamically loaded assembly which depends on the newer version for some reason e.g. users choice, is not loaded I will end up with unnecessary new assembly loaded in the process, perhaps not a big problem in this case, but could be in other cases).
I am using .Net 6 so loading into separate AppDomain is (afaik) not an option
mercredi 10 novembre 2021
Is there a way of dynamically iterating through a struct and modifying certain fields? [duplicate]
Suppose we have a struct that contains fields that are defined as structs also. In the example below, the Children
field of the Parent
struct is an array of pointers to the Child
struct too. How do I create a function that can take any arbitrary struct, recurse through it (flexible depth) and update all variables of a certain type (or pointer of a certain type)?
type Child struct {
Name string
Age int
Something *string
}
type Parent struct {
Name string
Surname *string
Children []*Child
PetNames []string
Parents [2]*Parent
Others []Child
Child
}
func sanitizeStringsInStruct(c interface{}, ssf func(string) string) {
v:= reflect.ValueOf(c)
val := v.Elem()
for i := 0; i < val.NumField(); i++ {
field := val.Field(i)
switch field.Kind() {
case reflect.String:
str := ssf(field.Interface().(string))
field.SetString(str)
case reflect.Interface:
fmt.Println("Interface")
case reflect.Struct:
fmt.Printf("Struct: %v %v\n", val.Type().Field(i).Name, val.Type().Field(i).Type)
// Skip private fields
if !field.CanInterface() {
continue
}
// Need assistance
case reflect.Slice:
varName := val.Type().Field(i).Name
varType := val.Type().Field(i).Type
if !field.CanInterface() {
continue
}
fmt.Println("Slice", reflect.ValueOf(field.Interface()), varName, varType
case reflect.Ptr:
// Need assistance
default:
varName := val.Type().Field(i).Name
varType := val.Type().Field(i).Type
varKind := val.Field(i).Kind()
fmt.Println("Some type: \t", varName, varType, varKind)
}
}
How should I fix the code above o support recursively iterating through slices, arrays and pointers?
Thanks
Check if an object class is a subclass of another class, but with generics
There has been a lot of similar questions on Stack Overflow, but I didn't find any with generics playing a role
abstract class A<T> {
public abstract T getT();
public void someMethod(Object value){
if(A.class.isAssignableFrom(value.getClass())
// either B or C work, as expected
if(A<Long>.isAssignableFrom(value.getClass()) // does not compile
// this should allow classes like B only
}
}
class B extends A<Long>{
long id;
@Override
public Long getT(){return id;}
}
class C extends A<Integer>{
int id;
@Override
public Integer getT(){return id;}
}
What I need is a way to distinguish between B and C when using some method, as shown in the second if
Get object type from enum value
I have an enum defined wich stores multiple class names. Is there a way I can get the the type of an object given the enum value? The method GetObjectType when called with parameter Types.A should return the type of class A, how should it's body look like?
public class A
{
}
public class B
{
}
public enum Types
{
A = 1,
B = 2
}
public Type GetObjectType(Types type)
{
}
RtFieldInfo.FieldType causes System.TypeLoadException: Could not load type 'SubClass' from assembly 'A...' because the format is invalid
I narrowed down the program to:
using System;
using System.Runtime.InteropServices;
abstract class Abstract {
public int a;
}
[StructLayout(LayoutKind.Sequential)]
sealed class TestClass : Abstract {
public int x;
}
sealed class Container {
public TestClass tc;
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("START");
foreach (var field in typeof(Container).GetFields()) {
Console.WriteLine($"{field.Name}: {field.FieldType}");
}
}
}
Outputs:
START
Unhandled exception. System.TypeLoadException: Could not load type 'TestClass' from assembly 'DEL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the format is invalid.
at System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
at System.Reflection.RtFieldInfo.InitializeFieldType()
at Program.Main(String[] args) in /code/Program.cs:line 27
Why does the exception happen? Can I use StructLayout on the subclass?
mardi 9 novembre 2021
C#10 - using the type T to switch in a generic method
There are lots of answers on how to switch on type in older versions of C#. My question has to do with how to switch on the type called out in a generic method:
public T GetAxis<T>(object axisObject)
{
switch (typeof(T))
{
case Axis:
//...do something
break;
}
return null;
}
I am getting an error on the line:
case Axis axis:
The error is:
The expression of type 'System.Type' cannot be handled by a pattern of type 'MyNamespace.Axis'.
I believe my question is how do I get the Type being called out in the <> specification so I can switch on it.
How to get all child objects of a class
Is it possible to retrieve a list of child objects (of a cetain type) of an object ?
For example in this code I have an App with several available Commands. A function print all availible commands this way the user knows what he can do.
I want to iterate over each object of type Command found in App to print his doc, this way the doc updates itself automatically every time a Command is added in App.
class Command {
public:
std::string Name;
std::string Description;
virtual void Compute() = 0;
};
class StartCommand : public Command {
std::string Name = "start";
std::string Description = "Start the process";
virtual void Compute() {
// Code to start the process
}
};
class StopCommand : public Command {
std::string Name = "stop";
std::string Description = "Stop the process";
virtual void Compute() {
// Code to stop the process
}
};
class App {
public:
StartCommand StartCommand;
StopCommand StopCommand;
void PrintAvailibleCommands() {
std::cout << "All availible commands are: " << std::endl;
for (Command command : this.GetObjects<Command>()) {
std::cout << command.Name << ": " << command.Description << std::endl;
}
}
};
It's the this.GetObjects<Command>()
function which does not exist and which I would like to implement.
Du you have an idea ?
Dynamically Test All Entity Framework Core DbContext DbSet<> objects with xUnit
I'm using xUnit and FluentAssertions to write an integration test to validate that our models are correctly mapped. We have dozens of EF contexts and for each context, there are one or more DbSet<>
properties like this:
public class SomeContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder builder) { // ... }
public virtual DbSet<User> Users { get; set; }
}
They are all laid out the same way so this would be an ideal candidate for using [MemberData]
to get each context dynamically as input to the test and the DbSet<>
property, invoke it, and just make sure it doesn't fail doing a simple query. The Container.GetInstance()
call is a call to my DI container to get the actual DbContext
object:
public class ContextTests
{
public static IEnumerable<object[]> EntitiesMappedInCode =>
typeof(DbContextInitializer).Assembly.GetTypes()
.Where(t => t.IsSubclassOf(typeof(DbContext)) && !t.IsAbstract)
.SelectMany(dbContextType =>
{
var context = (DbContext) Container.GetInstance(dbContextType);
var entities = context.Model.GetEntityTypes();
var dbSetProperties = context.GetType().GetProperties().Where(p =>
typeof(DbSet<>).IsAssignableFrom(p.PropertyType.GetGenericTypeDefinition()));
return dbSetProperties.Select(dbSet => new [] {context, dbSet.GetValue(context)});
});
[Theory]
[MemberData(nameof(EntitiesMappedInCode))]
public void EntitiesDefinedInCode_ExistsInDatabase(DbContext context, object dbSetObject)
{
var dbSet = dbSetObject as DbSet<dynamic>;
dbSet.Invoking(dbSet => Queryable.FirstOrDefault<dynamic>(dbSet))
.Should().NotThrow<SqlException>("the entity framework model should match the database");
}
}
The problem is the reflection does not work properly to give back the runtime instance and fails at p.PropertyType.GetGenericTypeDefinition()
with an error.
Has anyone dynamically retrieved the DbSet<>
properties of contexts and successfully invoked queries on them?
Reference an old assembly with .NET Core
We're trying to migrate our WPF app to .NET 6.0 from .NET 4.6.1 and keep getting a MissingMethodException
for DefineDynamicAssembly
when calling into an old, obfuscated third-party library we currently depend on. The library appears to be built on .NET 3.5.
The closest-sounding thing we googled for was this SO post about System.Reflection.Emit
, but we do not have the source code for the third-party library.
We are hoping there might be a way to finesse the library into working. Can anyone please offer insights?
Just to be clear, we don't care about deobfuscating the assembly. We just want it to work.
System.TypeInitializationException HResult=0x80131534 Message=The type initializer for 'A.c9a060eaf30c717bf2a2d42ef6a110a47' threw an exception. Source=assemblyName StackTrace: at A.c9a060eaf30c717bf2a2d42ef6a110a47.c8e61c0abc97221f783661115e77d8d32() at ThirdParty.Library.Repository.get_Default()
Inner Exception 1: TypeInitializationException: The type initializer for 'A.c11a752a126c751be2ef161586727cc33' threw an exception.
Inner Exception 2: MissingMethodException: Method not found: 'System.Reflection.Emit.AssemblyBuilder System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)'.
Reflection - trying to get a reference for class field to pass it as an argument
I'm trying to print public properties of an object which can be primitives or also an object by using Reflection I manage to print the methods and primitive fields but when I try to send recursively the field of type class I get an error(in line printProperties(o);).
example - public class A { public Class B }
How can I send a references of class B to printProperties ?
Class reflectClass = (Class) reflectObject;
String className = reflectClass.getName();
System.out.println(className);
Method [] classMethod = reflectClass.getMethods();
for(Method m :classMethod){
System.out.println("Name "+m.getName());
System.out.println("Return "+m.getReturnType());
}
System.out.println("Fields");
Field[] fields = reflectClass.getDeclaredFields();
for (Field f : fields){
if(f.getType().isPrimitive()||f.getType().isAssignableFrom(String.class)){
System.out.println("Field "+f.getName());
}
else {
Object o = f.get(this);
printProperties(o);
}```
Is there a way to obtain a "reference" to a value type field through reflection?
im trying to make a tool for Unity, which will display values from fields which have my custom [ObserveField]
attribute in the Editor window. I've got to a point where I have a list of needed FieldInfo
's but here's where my problem comes - at the moment I have to use fieldInfo.GetValue(fieldObject)
to obtain the values and if I do it for every field in the list, in a GUI loop, it's gonna slow down significantly and I assume its not the best idea.
I know that if a field would be of reference type, there would be no problem, but for now only value types will be possible to "observe". Is there a way to somehow obtain the "reference" to the actual value, not the copy? Maybe something like a c++ pointer to a memory address of a field value?
Generic information about interface implemented by field type in Java
Let's suppose we have a type CustomMap<A, B>
which extends CommonMap<C, D>
which in turn implements Map<E, F>
.
Naturally one would expect that A == C == E
, but it's not always so - you can have a CustomMap<V>
implementing Map<String, V>
for example.
The question is, let's suppose I have a Field
, and field.getType()
is some interface or class implementing Map<K, V>
. The type itself may be non generic, may be generic but with generic signature differing from <K, V>
, etc. How go I get K
and V
type parameters of Map
using reflection?
How to get fields names of a class inside another class?
We are creating CSV files from DTO classes, using reflection to get the names of all the column names. ClassName.class.getDeclaredFields()
gives us array of all column names.
We have a use case where, we have classes with composition relation, like below:
public class Book {
private String title;
private Author author;
}
public class Author {
private String name;
private Integer age:
}
Here Book is the root class, i.e., final CSV will be named books.csv
With Book.class.getDeclaredFields()
, we only get field names title and author, but we also want field names from Author class (name and age), is there a way to get those?
lundi 8 novembre 2021
How to get the value of a Type annotation
For example, here is a Type annotation called IntRange
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.TYPE_USE})
public @interface IntRange {
public int min() default 0;
public int max() default 5;
}
And here's a method which used it.
public boolean sumLessThan10(@ListLength(min = 0, max = 2) List<@IntRange(min = 5, max = 7) Integer> list) {
return true;
}
So how to get the value within @IntRange with reflection? And what if @IntRange is used in a nested list?
dimanche 7 novembre 2021
Read all information from a java source file using Java [duplicate]
I'm creating a program in java that need to read an external source java file.
My fist approach is to read that file as plain text. But as I want to extract all the information from that java source file, I'm applying regular expresions find the class name, extends, implements, attribute names/classes etc.
I'm wondering if there is a more direct way as I have the feeling I'm reinventing the wheel. I know it is possible to get all the information by using reflection with Class.forName. But it is not possible in this case, isn't it? As it is an external java source file so not part of the source code of my program.
Any idea?
Mapping SQLReader to nested custom classes using reflection
I have the following code which I found on here but I want it to work for classes that have custom type objects inside (class Person having a List of type Fields). What I am doing is, I tried to update the function so that I get all the members of the inner custom classes but I don't know how to combine them back into the original object. Also, if there is a better way to do this, kindly point me in the right direction. The new part is marked as 'starts from here'.
internal static async Task<IEnumerable<T>> ConvertToNestedObjectsAsync<T>(this SqlDataReader rd) where T : class, new()
{
Type type = typeof(T);
var accessor = TypeAccessor.Create(type);
var members = accessor.GetMembers();
var tList = new List<T>();
while (await rd.ReadAsync())
{
var t = new T();
for (int i = 0; i < rd.FieldCount; i++)
{
if (!rd.IsDBNull(i))
{
string fieldName = rd.GetName(i);
if (members.Any(m => string.Equals(m.Name, fieldName, StringComparison.OrdinalIgnoreCase)))
{
accessor[t, fieldName] = rd.GetValue(i);
}
else
{
//starts from here
foreach (Member mem in members.Where(mm => !IsPrimitive(mm.Type)).ToList())
{
var accessorNested = TypeAccessor.Create(mem.Type);
var membersNested = accessorNested.GetMembers();
if (membersNested.Any(mmm => string.Equals(mmm.Name, fieldName, StringComparison.OrdinalIgnoreCase)))
{
accessorNested[mem.Type, fieldName] = rd.GetValue(i);
}
}
}
}
}
tList.Add(t);
}
return tList;
}
internal static bool IsPrimitive(Type t)
{
return new[]
{
typeof(string),
typeof(char),
typeof(byte),
typeof(sbyte),
typeof(ushort),
typeof(short),
typeof(uint),
typeof(int),
typeof(ulong),
typeof(long),
typeof(float),
typeof(double),
typeof(decimal),
typeof(DateTime),
}.Contains(t);
}