Java reflection, what class does the object have? - java

im trying to do some reflection on a applet.
things i found are some arrays of ints, strings, objects etc.
for example, if there was a field with an object[] and object[0].toString() = [I#7593c366
then i know its an integer array. but what if it says aa#98324ca33 is it's class then aa?
im using a classloader, so my first guess when i see this i need to load the aa class (part before the #, and use the object in it. but im not sure the part befor the # is the class. can somebody say me this is right? or got other ideas?
thnx!

You shouldn't use toString() for this - for one thing, it can have been overridden. As a straightforward example:
Object x = "aa#98324ca33";
String bogusClassName = x.toString();
You would clearly be wrong to think that x refers to an object of type aa here - it refers to a string.
You can find out the class of any object just by calling getClass() on it:
Object x = new SomeType();
Class<?> clazz = x.getClass();
It's not really clear what you're trying to do or where you're getting information from in the first place, but you definitely shouldn't be using toString to determine the class involved.

Yes, the part before # is the class fqn, but you should not rely on that. Object can override toString() and then your logic will fail.
Use obj.getClass() instead.

Take a look at the class java.lang.Class. Just call getClass on an object to retrieve its class instead of using the toString method
Object anObject = ... ;
Class<?> clazz = anObject.getClass();
If you want to check whether it is an array, you can use to Class#isArray() method
clazz.isArray()
The other way around is also possible. If you have a Class instance, you can determine whether an object belongs to this class by using the Class#isInstance( Object ) method
clazz.isInstance( anObject );

Related

Instantiate 'this' Object

I'm trying to load a serialized object within the class using a method like this one:
private void loadCatalog(MyClass myClassNew)
{
this = myClassNew;
}
So I have this method in my MyClass, and I receive as a parameter an object having the type of MyClass. How can I do something like above? The code above gives me an error of which I'm not sure why. The object myClassNew is the same as the one before serializing, so I'm sure that I receive a valid object of type MyClass.
There is no way to do that. You must write code that copies each instance field of MyClass from the argument to this. For instance:
this.firstName = myClassNew.firstName;
this.lastName = myClassNew.lastName;
You could use reflection do to this, but you probably shouldn’t. Unless MyClass is very simple, you may find that some fields require special handling. For example, copying a List reference would be very bad, unless it’s an unmodifable List, as the two objects should share a reference to the same List object.
You will get an error:
The left-hand side of an assignment must be a variable
"this" is not a variable that you can assign to. you can create fields in the object and do "this.field1 = myClassNew", but you cannot assign to "this".

What does .class mean in Java?

What does .class mean in Java? For example, if I created a class called Print. What does Print.class return?
When you write .class after a class name, it references the class literal -
java.lang.Class object that represents information about a given class.
For example, if your class is Print, then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print.
Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());
.class is used when there isn't an instance of the class available.
.getClass() is used when there is an instance of the class available.
object.getClass() returns the class of the given object.
For example:
String string = "hello";
System.out.println(string.getClass().toString());
This will output:
class java.lang.String
This is the class of the string object :)
Just to clarify, this '.class' method is not referring to the bytecode file you see after compiling java code nor a confusion between the concepts of Class vs. Object in OOP theory.
This '.class' method is used in Java for code Reflection. Generally you can gather meta data for your class such as the full qualified class name, list of constants, list of public fields, etc, etc.
Check these links (already mentioned above) to get all the details:
https://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html
Normally you don't plan on using Reflection right away when you start building your project. It's something that you know you need after trying to manage already working code. Many times you need it to manage multiple instances of your program. Maybe you want to identify each particular 'clone' to determine if something is already defined, or count the number of functions, or just simply log the details of a particular instance of your class.
If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass()
The .class Syntax
If the type is available but there is no instance then it is possible to obtain a Class by appending .class to the name of the type. This is also the easiest way to obtain the Class for a primitive type.
boolean b;
Class c = b.getClass(); // compile-time error
Class c = boolean.class; // correct
See: docs.oracle.com about class
If there is no instance available then .class syntax is used to get the corresponding Class object for a class otherwise you can use getClass() method to get Class object. Since, there is no instance of primitive data type, we have to use .class syntax for primitive data types.
package test;
public class Test {
public static void main(String[] args)
{
//there is no instance available for class Test, so use Test.class
System.out.println("Test.class.getName() ::: " + Test.class.getName());
// Now create an instance of class Test use getClass()
Test testObj = new Test();
System.out.println("testObj.getClass().getName() ::: " + testObj.getClass().getName());
//For primitive type
System.out.println("boolean.class.getName() ::: " + boolean.class.getName());
System.out.println("int.class.getName() ::: " + int.class.getName());
System.out.println("char.class.getName() ::: " + char.class.getName());
System.out.println("long.class.getName() ::: " + long.class.getName());
}
}
I think the key here is understanding the difference between a Class and an Object. An Object is an instance of a Class. But in a fully object-oriented language, a Class is also an Object. So calling .class gets the reference to the Class object of that Class, which can then be manipulated.
Adding to the above answers:
Suppose you have a a class named "myPackage.MyClass". Assuming that is in classpath, the following statements are equivalent.
//checking class name using string comparison, only Runtime check possible
if(myInstance.getClass().getName().equals(Class.forName("myPackage.MyClass")).getName()){}
//checking actual Class object for equality, only Runtime check possible
if(myInstance.getClass().getName() == Class.forName("myPackage.MyClass"))){}
//checking actual Class object for equality, but compile time validation
//will ensure MyClass is in classpath. Hence this approach is better (according to fail-fast paradigm)
if(myInstance.getClass() == MyClass.class){}
Similarly, the following are also equivalent.
Class<?> myClassObject = MyClass.class; //compile time check
Class<?> myClassObject = Class.forname("myPackage.MyClass"); //only runtime check
If JVM loads a type, a class object representing that type will be present in JVM. we can get the metadata regarding the type from that class object which is used very much in reflection package. MyClass.class is a shorthand method which actually points to the Class object representing MyClass.
As an addendum, some information about Class<?> reference which will be useful to read along with this as most of the time, they are used together.
Class<?> reference type can hold any Class object which represents any type.
This works in a similar fashion if the Class<?> reference is in method argument as well.
Please note that the class "Class" does not have a public constructor. So you cannot instantiate "Class" instances with "new" operator.
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.
One of the changes in JDK 5.0 is that the class java.lang.Class is generic, java.lang.Class Class<T>, therefore:
Class<Print> p = Print.class;
References here:
https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html
http://docs.oracle.com/javase/tutorial/extra/generics/literals.html
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.2

Working with the class keyword in Java

I don't really understand how the class keywords work in some instances.
For example, the get(ClientResponse.class) method takes the ClientResponse.class. How does it use this when it gets it, and what are the advantages over just passing an instance of it?
SomeClass.class
returns a Java Class object. Class is genericized, so the actual type of SomeClass.class will be Class<SomeType> .
There are lots of uses for this object, and you can read the Javadoc for it here: http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html
In ClientResponse.class, class is not a keyword, neither a static field in the class ClientResponse.
The keyword is the one that we use to define a class in Java. e.g.
public class MyClass { } /* class used here is one of the keywords in Java */
The class in ClientResponse.class is a short-cut to the instance of Class<T> that represents the class ClientResponse.
There is another way to get to that instance for which you need an instance of ClientResponse. e.g
ClientResponse obj = new ClientResponse();
Class clazz = obj.getClass();
what are the advantage over just passing a instance of it?
In the above example you can see what would happen in case obj was null (an NPE). Then there would be no way for the method to get the reference to the Class instance for ClientResponse.
The Class class, which is different from the class keyword, is meta-data describing instances. It tells you about the methods, data members, constructors, and other features of the instances that you create by calling new.
For example get(ClientResponse.class) method takes the
ClientResponse.class how does it uses this when it gets it and what
are the advantage over just passing a instance of it?
You can't pass an instance of ClientResponse to this method; it's expecting meta-data about all instances of ClientResponse. If you passed an instance, you'd expect that the method might change the state of that instance. But passing the meta-data about all instances might allow the method to create a new kind of instance (e.g. a dynamic proxy) or do something else that depends on the meta-data about all instances of ClientResponse. See the difference?
A class is a "blueprint" of the object. The instance is a object.
If we have
public class SomeClass {
int a;
SomeClass(int a) {
this.a = a
}
}
We can have an instance of this class
SomeClass c = new SomeClass(10);
c is an instance of the class. It has a integer a with value 10.
The object SomeClass.class represents a Class.
Here SomeClass.class is a object of the type Class which has the information that SomeClass is
a concrete class with
one constructor
with a integer member variable
and lots more other metadata about the class SomeClass. Note that it does not have a value for a.
You should use get(c) incase you are planning to do something with a instance of c like call c.a or other useful functions to manupulate/get data of the instance.
You should use get(SomeClass.class) when the get returns something based on the fact that the argument is some type of class. For example, if this is a method on a Registry class which has a map which retrieves a implementation class based on type of class passed in.
The very most important fact is - you don't need to have an instance to call the method. It's critically useful in situations when you cannot for some reason instantiate a class, e.g. it's abstract, or have only private constructor, or can only be correctly instantiated by some framework, like Spring or JSF.
You can then call get to obtain an object of a requested type without even knowing where it does come from and how it get's created.
Here ClientResponse.class is an instance of Class<ClientResponse>. In general Class object represents type of an object. When you create new instance:
Object obj = new ClientResponse()
you can retrieve the class (type) of that object by calling:
obj.getClass()
So, why would you pass Class objects around? It's less common, but one reason is to allow some method create arbitrary number of instances of a given class:
ClientResponse resp = ClientResponse.newInstance();
There's a lot of ways Class objects can be used. This is used for Reflection. Below is a link that can help you understand more.
http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html
Whenever we compile any Java file, the compiler will embed a public, static, final field named class, of the type java.lang.Class, in the emitted byte code. Since this field is public and static, we can access it using dotted notation along with class name as in your case it is ClientResponse.class.

is it possible to get the class of the interface <Set>

Am having some arguments say (String a, Treeset b, Set c)
and I try to get the class by arguments[i].getClass(); of the above arguments..
is Iit possible to get the class of the interface <Set>.
For example:
Class[] argumentTypes = new Class [arguments.length];
for (int i = 0 ; i < arguments.length ; i++)
{
argumentTypes[i] = arguments[i].getClass();
}
The code you've given will find the classes of the arguments (i.e. the values provided to the method) - but those can never be interfaces; they'll always be concrete implementations. (You can never pass "just a set" - always a reference to an object which is an instance of an implementation of the interface, or a null reference.)
It sounds like you want the types of the parameters - which you'd get via reflection if you absolutely had to, finding the Method and then getting the parameters from that with getParameterTypes. But given that you're within the method, you already know the parameter types, because they're at the top of the method... I'm not sure the best way of finding "the currently executing" method, if that's what you're after.
If you're just trying to get the class associated with Set, you can use Set.class of course. But again, it's not really clear what you're trying to do.
EDIT: Okay, judging from your comment, there are some logical problems with what you're trying to do. Going from the values of arguments to which method would be invoked is impossible in the general case, because you've lost information. Consider this, for example:
void foo(String x) {}
void foo(Object y) {}
foo("hello"); // Calls first method
foo((Object) "hello"); // Calls second method
Here the argument values are the same - but the expressions have a different type.
You can find all methods which would be valid for the argument values - modulo generic information lost by type erasure - using Class.isAssignableFrom. Does that help you enough?
Note that you'll also need to think carefully about how you handle null argument values, which would obviously be valid for any reference type parameter...
You can use http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#getInterfaces()
You will get the class what the caller provided.
I mean,in below class you will get HashSet.
Set set=new HashSet();
System.out.println(set.getClass());
You can do this in two ways given below
Set s = new //any class that implements it for example HashSet or TreeSet etc.;
s.getClass().getName(); //This will return the name of the subclass which is refered by s.
or if in other way can do it
Set s = null;
s.getClass();//This causes NullPointer Exception

How to store a reference to a class in Java?

Is there any way in Java to store a reference to a class? Here's what I want to do:
public class Foo
{
public static void doSomething() {...}
};
SomeClass obj = Foo;
obj.doSomething();
Is there some class "SomeClass" which lets me store a reference to a class, such that I can later use that stored object to call a static member of the original class?
The obvious thing would be class Class:
Class obj = Foo.class;
obj.someMember().doSomething();
but I haven't figured out which of class Class's members might act as "someMember()"... none of them, I think.
Does anyone know if what I'm trying to do is possible in Java?
You can dynamically get a method from a Class object using the getMethod() methods on the class. If a method is static, then the "object" parameter of "invoke" will be null.
For example, the "obj.someMember()" above would be something like this:
obj.getMethod("someMember", null).invoke(null, null);
The extra nulls are because your method requires no parameters. If your method takes parameters, then they will need to be passed in accordingly.
This will throw various checked exceptions, so you'll need to handle those as well.
Once you've invoked the method, it will return an Object. You'll want to cast that to whatever type you're expecting, and then you'll be able to run the "doSomething()" method directly on that.
This is using a trick called reflection, if you'd like to read up more on it. :)
If you are using jdk1.5 or above, annotation will be a choice when you want to get metadata of Class.

Categories