logo
down
shadow

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


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

By : user2954211
Date : November 22 2020, 01:01 AM
fixed the issue. Will look into that further You need to create an instance. One way is via c.newInstance, which if this is a JavaBean should be all you need (it attempts to invoke the zero-args constructor for the class). Otherwise, you need to find an appropriate constructor via getDeclaredConstructor/getDeclaredConstructors or similar and then invoke them to get an instance.
Re your question in a comment:
code :
public class Foo {
    public int a;
    public int b;
}
Class f = Class.forName("Foo");
Object inst = f.newInstance();
Field aField = f.getDeclaredField("a");
aField.setInt(inst, 42);
Field bField = f.getDeclaredField("b");
bField.setInt(inst, 67);


Share : facebook icon twitter icon
Setting a field on an object that is a property in a class using reflection in .NET

Setting a field on an object that is a property in a class using reflection in .NET


By : Dan
Date : March 29 2020, 07:55 AM
I wish this help you Well, this isn't all that difficult to do sort of correctly, but it would get really messy if you wanted argument-validation, graceful error-handling etc. Here's an example that should highlight the technique (no checks):
code :
static void SetBsAsWhoToCsWho(object b, object c)
{
    // csWho = c.Who
    object csWho = c.GetType().GetProperty("Who").GetValue(c, null);

    // a = b.Information
    object a = b.GetType().GetProperty("Information").GetValue(b, null);

    // a.Who = csWho
    a.GetType().GetProperty("Who").SetValue(a, csWho, null);
}
Java reflection: how to get field value from an object, not knowing its class

Java reflection: how to get field value from an object, not knowing its class


By : Chris Perez
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Say, I have a method that returns a custom List with some objects. They are returned as Object to me. I need to get value of a certain field from these objects, but I don't know the objects' class. , Assuming a simple case, where your field is public:
code :
List list; // from your method
for(Object x : list) {
    Class<?> clazz = x.getClass();
    Field field = clazz.getField("fieldName"); //Note, this can throw an exception if the field doesn't exist.
    Object fieldValue = field.get(x);
}
List<Foo> list; //From your method
for(Foo foo:list) {
    Object fieldValue = foo.fieldName;
}
List list;
for(Object x: list) {
   if( x instanceof Foo) {
      Object fieldValue = ((Foo)x).fieldName;
   }
}
Using reflection, get the parent class/field of an object

Using reflection, get the parent class/field of an object


By : Sky
Date : March 29 2020, 07:55 AM
I wish this help you This is not possible/feasible in general.
The same object instance can have many names - that is, the same object can be assigned to many different static fields, instance fields, parameters, local variables (etc) simultaneously.
Can a Field class from Java reflection work on any object?

Can a Field class from Java reflection work on any object?


By : LaBamba
Date : March 29 2020, 07:55 AM
wish help you to fix your issue This is perfectly fine and it's supposed to work this way. A Field refers to a field in a specific class, not a specific instance (object) of that class - so you can use it with any instance of the class.
Ofcourse, if the Field refers to a field in class Test, then you can only use it on objects of type Test. You would get an IllegalArgumentException if you would try to call get(Object o) on the Field passing it something else than a Test object.
cannot get package and class name if object class is array on field using java reflection

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


By : Siyamak
Date : March 29 2020, 07:55 AM
I wish did fix the issue. An array is a special type. It does not belong to any package.
Try (untested):
code :
Class cls=Class.forName("example");
Field[]f=cls.getDeclaredFields();
for(Field field : f){
     Class<?> type = field.getType()
     int numArrayDimensions= 0;
     while (type.isArray()){
        type = type.getComponentType();
        numArrayDimensions++;
     }
     if (! type.isPrimitive()){
         Package pkg = type.getPackage();
     }
     String className = getFormattedClassName(type, numArrayDimensions);

}

private String getFormattedClassName(Class<?> type, int numArrayDimensions){
         StringBuilder sb = new StringBuilder(type.getName());
         IntStream.range(0, numArrayDimensions).foreach(dimension -> sb.append("[]"));
         return sb.toString();
}
Related Posts Related Posts :
  • How to write generic Java API without method Overloading
  • Java Serialization / Deserialization of an ArrayList works only on first program execution
  • Conway's Game of Life's rules dont apply properly
  • call a java method when Click on a html button without using javascript
  • Why does SSLSocketFactory.createSocket returns a Socket instead of SSLSocket?
  • How to schedule a task in Tomcat
  • compare two pdf files (approach) using java
  • What is the use of allowCoreThreadTimeout( ) in ThreadPoolExecutor?
  • Describe the Strategy Design Pattern in Java?
  • MongoDB too many open connections
  • Issue with generate JAXB classes with value constructors
  • Moving from one frame to another in java swing
  • Get a thread by Id
  • how to open front camera and back camera at same time?
  • Messed up with Java Declaration
  • Extracting chart in EXcel as image using java
  • How to get latitude and longitude in Android phone?
  • Do GC pauses and kill -STOP produce the same behavior?
  • Android HTML.ImageGetter Images resized
  • The way to instantiate map<String, List<String>> in Java
  • Java Making objects move while buttons held
  • Androidx Navigation View - `setNavigationItemSelectedListener` Doesn't Work
  • after compiling code JFrame does not appear
  • Netbeans project, JFrames ran from the main JFrame close all JFrames in project
  • Square Retrofit Client: How to enable/disable followRedirects? How to intercept redirect URL?
  • Java Circular Reference - Can’t Compile
  • Mouse click on specific time JAVA
  • android 4 onCreateDialog return type incompatible when overriding
  • Java Implementation of Oracle's DBMS_UTILITY.GET_HASH_VALUE Function
  • javac cannot be run, and furthermore does not seem installed
  • Function to obtain a thread given its ID
  • Java File path to Executable has spaces
  • Minimum Oracle Java VM heap memory setting?
  • Elegant way to create one of a large number of classes
  • Java fx binding styles
  • Summing weights based on string in large file
  • Android ListView setOnItemClickListener not working
  • How is the Java Bootstrap Classloader loaded?
  • Check object is blank
  • Add image between text in JEditorPane
  • Java POI Excel creating new column and new rows
  • NullPointerException when managing bean with Spring+JSF(Primefaces)
  • Content autocomplete in spring tool suite 4
  • Super Noob Help ~ MouseEvent/Frame
  • Making one project with dependencies stand-alone in Eclipse (Java)
  • Jsoup- getting certain attributes from website
  • MongoDB, how to make a link between collections with JAVA code
  • Overriding an abstract method means class abstract class or not in java?
  • Bukkit teleport - nullPointerException
  • How to check if a Float variable is negative in java
  • Servlet: Cannot forward after response has been committed
  • sql query to select a specific cell in excel
  • How to make new picture when mouse dragged in java
  • Use Constants interface in GWT Project
  • Setting size of a JPanel in GroupLayout
  • Construct a map from two equal size arrays
  • Implementing Read-Write Locks with Double-Checked Locking
  • Disable NO_BUTTON from JOptionPane Java if a condition is true
  • UDP multiple socket
  • Android Threading: This Handler class should be static or leaks might occur
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org