Check if Field is from specific class - java

To display keys & values of a dataobject, I'm using a Collection of AccessibleObjects to generate a table. The AccessibleObject'S are collected on a specific time, but the values are read, when the render have to render the table.
The Problem: I'm not only want to hold AccessibleObject's of one specific Class. Is it possible to check a AccessibleObject Class-Origin? e.g. accessibleObject.fromClass(classType);

Do you mean
Member member = field or method;
Class clazz = member.getDeclaringClass()
to get the class the field appears in.
Note: this is the actual class, not the class you might have used to look it up. e.g. say A has a field x and a subclass B. If you get field x of class B, it will say the declaring class is A. This is because A and B can have a field called x.

Class c = field.getDeclaringClass();
From JavaDoc:
Returns the Class object representing the class or interface
that declares the field represented by this Field object.

Related

Java get field names into a method from different class, where method existing class is extended

As far i know this is not possible, but still posting here just to understand is there any solution already tried by stack members. If i could able to do this, that helps to print some meaning full logs in my selenium based testing project, instead of printing code level xpaths and element IDs
So here what i have in my current code.
Class A having all generic methods defined to use in other classes.
public class classA {
public void someAction(String elementIdentification){
//doing some acctions using elementIdentification
}
}
Class B extended the Class A and used the methods from class A by passing parameters. In Class B these parameters are declared at top of the Class in the form of fields or Constants.
public class classB extends classA{
//100 to 200 fields are declared like below
private String RESEARCH_BUTTON = "BUT_23BB8DDB79FD1C6237315";
private String TRYAGAIN_BUTTON = "//h2[#id='C2__C3__HEAD_5F3EC642AC086D0C23576']";
public void classBMethods(){
someAction(TRYAGAIN_BUTTON );
}
}
Now when ever i run the test, if method fails its printing as
"failed to identify //h2[#id='C2__C3__HEAD_5F3EC642AC086D0C23576']"
and this doesn't give any meaning full information on first glance. Instead of this if i could able to retrieve name i.e "TRYAGAIN_BUTTON", so that i can implement logic to print these values in logs and that will be easier when executed batch cases for identifying the root cause of failure.
if it is one OR two place, i could have written different logic passing extra parameter as separate name. but now we already developed the code as
ClassA method used at multiple places with different filed values from same ClassB,
Also ClassA extended to multiple classes like C and D.
Thanks in advance for the help.
Use an enum instead of just a String to define your elements. The getValue() is a custom method in the enum, while name() is built-in.
Then you can write code like
public enum Element {
String value;
RESEARCH_BUTTON("BUT_23BB8DDB79FD1C6237315")
// Add constructor and getValue() method
}
public void someAction(Element element){
String val = element.getValue(); // returns the string
String name = element.name(); // returns RESEARCH_BUTTON
}
Sorry for late reply, but i resolved the issue in other way by using the reflections api with min refactoring. By writing a class with reflections that accepts B object.
In ref class i stored all declared fields from Class B into HashMap in reverse order, i.e Variable value as Key & Variable name as value
So in my B class when ever i pass a variable, that passes as value into ref class, and there it looks into hash map for matching key, If matching key is found then respective value is name of my variable from B class.
This value i can use in A to print some meaning full logs.

What is an attribute in Java?

I read that to get length of an array, I use the length attribute, like arrayName.length. What is an attribute? Is it a class?
An attribute is another term for a field. It's typically a public constant or a public variable that can be accessed directly. In this particular case, the array in Java is actually an object and you are accessing the public constant value that represents the length of the array.
A class is an element in object oriented programming that aggregates attributes(fields) - which can be public accessible or not - and methods(functions) - which also can be public or private and usually writes/reads those attributes.
so you can have a class like Array with a public attribute lengthand a public method sort().
Attribute is a public variable inside the class/object. length attribute is a variable of int type.
Attributes is same term used alternativly for properties or fields or data members or class members.
An attribute is an instance variable.
In this context, "attribute" simply means a data member of an object.
Attribute is a synonym of field for array.length
Attributes are also data members and properties of a class. They are Variables declared inside class.
A class contains data field descriptions (or properties, fields, data members, attributes), i.e., field types and names, that will be associated with either per-instance or per-class state variables at program run time.
An abstract class is a type of class that can only be used as a base class for
another class; such thus cannot be instantiated. To make a class abstract,
the keyword abstract is used. Abstract classes may have one or more
abstract methods that only have a header line (no method body). The method
header line ends with a semicolon (;). Any class that is derived from the base
class can define the method body in a way that is consistent with the header
line using all the designated parameters and returning the correct data type
(if the return type is not void). An abstract method acts as a place holder; all
derived classes are expected to override and complete the method.
Example in Java
abstract public class Shape
{
double area;
public abstract double getArea();
}
■ What is an attribute?
– A variable that belongs to an object.Attributes is same term used alternatively for properties or fields or data members or class members
■ How else can it be called?
– field or instance variable
■ How do you create one? What is the syntax?
– You need to declare attributes at the beginning of the class definition, outside of any method. The syntax is the following:
;

Java reflecting nested anonymous classes

Why does this code return "class java.lang.Object" ?
Object a = new Object() {
public Object b = new Object(){
public int c;
};
};
System.out.println(a.getClass().getField("b").getType());
Why does the inner-inner type get lost? How can I reflect the c field ?
Edit:
This one works (as pointed out in some answers):
a.getClass().getField("b").get(a) ...
But then I have to invoke a getter, is there any way to reflect c with only reflection meta data?
Because b is declared as Object:
public Object b = ...;
There is a distinction between type of variable (static type) and type of the object referenced by that variable (runtime type).
Field.getType() returns static type of the field.
If you want to get runtime type of the object referenced by the field, you need to access that object and call getClass() on it (since a is declared as Object and therefore b is not visible as its member you have to use reflection to access it):
System.out.println(
a.getClass().getField("b").get(a).getClass());
UPDATE: You can't reflect c without accessing the instance of object containing it. That's why these types are called anonymous - a type containing c has no name, so that you can't declare field b as a field of that type.
Let's look at this line carefully:
System.out.println(a.getClass().getField("b").getType());
First, your take the a variable. It is of some anonymous subclass of the Object. Let's call that class MyClass$1. Okay, so far so good.
Next, you call the getClass() method. It returns the class of a, that is, a description of the MyClass$1 class. This description is not tied to any particular instance of that class, though. The class is the same for all instances, be it a or whatever else (unless different class loaders are used). In this particular case, however, there can be only one instance, because the class is anonymous, but the mechanism is still the same.
Now, from the class, you get the field b. As the class isn't directly tied to any of this instances, the field has nothing to do with a either. It's just a description of what exactly the field a of the class MyClass$1 is.
Now you get its type. But since it isn't tied to any instance, it can't know the runtime type. In fact, if the class wasn't anonymous, you could have numerous instances of MyClass$1, each having different value in a. Or you could have no instances at all. So the only thing getType() can possibly tell you is the declared type of b, which exactly what it does. The b field could in fact be null at that point, and you'd still get Object as the result.
The Field class provides the get() method to actually access that particular field of some object, like this:
System.out.println(a.getClass().getField("b").get(a).getClass());
Now you get something like MyClass$1$1, which is the name of the anonymous class of the object that field b references to, in the a instance.
Why does the inner-inner type get lost?
Because you are getting the type type of the field "b" (Object), not the type of the anonymous inner class of which you assigned the instance to "b".
How can I reflect the c field ?
You could use this
System.out.println(a.getClass().getField("b").get(a).getClass().getField("c"));
instead. This gets the value of the field "b" and it's class, but this only works if "b" is guaranteed be not null.
Doing this seems to indicate a bad design, there might be other ways to archive what you want to do with this. But without knowing the purpose, this is everything I can answer.

what is the Class object (java.lang.Class)?

The Java documentation for Class says:
Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
What are these Class objects? Are they the same as objects instantiated from a class by calling new?
Also, for example object.getClass().getName() how can everything be typecasted to superclass Class, even if I don't inherit from java.lang.Class?
Nothing gets typecasted to Class. Every Object in Java belongs to a certain class. That's why the Object class, which is inherited by all other classes, defines the getClass() method.
getClass(), or the class-literal - Foo.class return a Class object, which contains some metadata about the class:
name
package
methods
fields
constructors
annotations
and some useful methods like casting and various checks (isAbstract(), isPrimitive(), etc). the javadoc shows exactly what information you can obtain about a class.
So, for example, if a method of yours is given an object, and you want to process it in case it is annotated with the #Processable annotation, then:
public void process(Object obj) {
if (obj.getClass().isAnnotationPresent(Processable.class)) {
// process somehow;
}
}
In this example, you obtain the metadata about the class of the given object (whatever it is), and check if it has a given annotation. Many of the methods on a Class instance are called "reflective operations", or simply "reflection. Read here about reflection, why and when it is used.
Note also that Class object represents enums and intefaces along with classes in a running Java application, and have the respective metadata.
To summarize - each object in java has (belongs to) a class, and has a respective Class object, which contains metadata about it, that is accessible at runtime.
A Class object is sort of a meta object describing the class of an object. It is used mostly with the reflection capabilities of Java. You can think of it like a "blueprint" of the actual class. E.g. you have a class Car like this:
public class Car {
public String brand;
}
You can then construct a Class object which describes your "Car" class.
Class myCarClass = Class.forName("Car");
Now you can do all sorts of querying on your Car class on that Class object:
myCarClass.getName() - returns "Car"
myCarClass.getDeclaredField("brand") - returns a Field object describing the "brand" field
and so on. Every java object has a method getClass() which returns the Class object describing the Class of the Java object. So you could do something like:
Car myCar = new Car();
Class myCarClass = myCar.getClass();
This also works for objects you don't know, e.g objects you get from the outside:
public void tellMeWhatThisObjectsClassIs(Object obj) {
System.out.println(obj.getClass().getName());
}
You could feed this method any java object and it will print the actual class of the object you have given to it.
When working with Java, most of the time you don't need to worry about Class objects. They have some handy use cases though. E.g. they allow you to programmatically instanciate objects of a certain class, which is used often for object serialization and deserialization (e.g. converting Java Objects back and forth to/from XML or JSON).
Class myCarClass = Class.forName("Car");
Car myCar = myCarClass.newInstance(); // is roughly equivalent to = new Car();
You could also use it to find out all declared fields or methods of your class etc, which is very useful in certain cases. So e.g. if your method gets handed an unknown object and you need to know more about it, like if it imlements some interface etc, the Class class is your friend here.
So long story short, the Class, Field, Method, etc. classes which are in the java.lang.reflect package allow you to analyze your defined classes, methods, fields, create new instances of them, call methods all kinds of other stuff and they allow you to do this dynamically at runtime.
getClass() is a method that returns an object that is an instance of java.lang.Class... there is no casting involved. Casting would look like this:
Class<?> type = (Class<?>) object;
I would also like to add to ColinD 's answer that getClass will return the same object for instances of same type. This will print true:
MyOtherClass foo = new MyOtherClass();
MyOtherClass bar = new MyOtherClass();
System.out.println(foo.getClass()==bar.getClass());
Note that it is not equals, I am using ==.
In order to fully understand the class object, let go back in and understand we get the class object in the first place. You see, every .java file you create, when you compile that .java file, the jvm will creates a .class file, this file contains all the information about the class, namely:
Fully qualified name of the class
Parent of class
Method information
Variable fields
Constructor
Modifier information
Constant pool
The list you see above is what you typically see in a typical class. Now, up to this point, your .java file and .class file exists on your hard-disk, when you actually need to use the class i.e. executing code in main() method, the jvm will use that .class file in your hard drive and load it into one of 5 memory areas in jvm, which is the method area, immediately after loading the .class file into the method area, the jvm will use that information and a Class object that represents that class that exists in the heap memory area.
Here is the top level view,
.java --compile--> .class -->when you execute your script--> .class loads into method area --jvm creates class object from method area--> a class object is born
With a class object, you are obtain information such as class name, and method names, everything about the class.
Also to keep in mind, there shall only be one class object for every class you use in the script.
Hope this makes sense
A Class object is an instance of Class (java.lang.Class). Below quote taken from javadoc of class should answer your question
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
Let's take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't know what object will be returned from this method

Understanding the concept of inheritance in Java

I am just refreshing the oops features of the java. So, I have a little confusion regarding inheritance concept. For that I have a following sample code :
class Super{
int index = 5;
public void printVal(){
System.out.println("Super");
}
}
class Sub extends Super{
int index = 2;
public void printVal(){
System.out.println("Sub");
}
}
public class Runner {
public static void main(String args[]){
Super sup = new Sub();
System.out.println(sup.index+",");
sup.printVal();
}
}
Now above code is giving me output as : 5,Sub.
Here, we are overriding printVal() method, so that is understandable that it is accessing child class method only.
But I could not understand why it's accessing the value of x from Super class...
Thanks in advance....
This is called instance variable hiding - link. Basically you have two separate variables and since the type of the reference is Super it will use the index variable from Super.
Objects have types, and variables have types. Because you put:
Super sup = new Sub();
Now you have a variable sup of type Super which refers to an object of type Sub.
When you call a method on an object, the method that runs is chosen based on the type of the object, which is why it prints "Sub" instead of "Super".
When you access a field in an object, the field is chosen based on the type of the variable, which is why you get 5.
index is simply a field belonging to the parent class. Because it belongs to the parent class, it means that it's an attribute to all the children.
To simply the concept:
A Class Animal could have a field age and a field name
All sub classes would share those attributes, but would have additional field(s), which would be contained into those children classes only. For example hairColour could be the only attribute of the Dog class, but not to the class Snake, which could have a simple unique attribute venomous
In this structure all Animal have a name, and an age, which is what could define Animals in general, an each specie have some extra attribute(s) unique to them, which are contained into their respective sub classes.
Your code doesn't clearly show this, as your sub class has no constructor, indeed no super constructor call. As explained by Petar, your none private attribute index is access from the super class
This happens coz functions follows runtime binding whereas variables are bound at compile time.
So the variables depend on the reference's datatype whereas the functions depend on the value represent by the reference's datatype.
When we assigning the object of sub class to parent class object only the common property both class can be accepted by the parent class object , is called as object slicing
that's why the value of patent class 5 is printed its only happen with property not a method

Categories

Resources