.class - what is this construction and how it works? - java

I am beginner in programming and i just started working with greenfoot (software for creating games using Java). When i was writing code i had to use construction builded in greenfoot which was using parameter described as: java.lang.class where i had to type ClassName.class . I was trying to go through documentation and a lot of other sources to figure out how it works and what is this, but to be honest i couldnt understand anything. Is there is someone who can tell me in simply words what does it mean and how construction like ClassName.class works? That is the first time i see dot notation used like this, before I have seen only dot notation when i tried to refer to for example other class method like: OtherClass.method() . So is it just builded in instance variable of every class or something like this? Thanks in advance

It's called a class literal. ClassName.class provides access to the instance of Class that represents the given class. So for instance, String.class refers to the Class instance for the String class. Using that object, you can do do various things (like find out what its members are at runtime via reflection). (FWIW, objects provide also access to the Class instance for their class via their getClass method.)

Related

Loading a compiled class in Java and deserializing it's instance from a file

I need to have an app that during run-time can load another class and deserialize one of it's instance successfuly so that it can run it's methods and read the member variables.
From what I noticed, you can not serialize methods in Java, so I'm thinking about serializing the class instance in project2, load the compiled class with ClassLoader in project1, instantiate it and assign the deserialized instance from porject2 in project1 to the instantiated loaded class.
The serialized class will inherit the same parent class in both projects.
Is this the best way to go? It's a school project so the requirements are that my app can accept any other type of class without changing the code.
TL;DR: My plan is to load a compiled class with the ClassLoader so that my project knows about that class (specifically the methods inside) and then load that serialized class instance inside the project so that I can get the data from the instance and together with the loaded class (now I know the methods aswell), run the methods on the deserialized instance.
You are mistaken. The ability to call a method on some object isn't related to serialization at all.
What I mean: the method implementation is not part of the serialized data! Java serialization only writes field data into that output stream.
The implementation of a method only depends on the class file of some Java class. You can serialize and deserialize your objects as often as you want to - but what happens when you call a method on such an object is only determined by the class file that the corresponding class loader loaded for you when first accessing the corresponding class.
If your goal is really just about "one class dumps an object into a binary representation"; and another piece of code loads that binary data; turns it into an object; to access that object; then you do not need two projects. You also do not need to worry about "the methods being" there. As long as your ClassLoader knows the class of objects to be de-serialized, everything will just work. Just pick an example tutorial, like this here and work through it.
But: when your requirement is to invoke methods or access fields of arbitrary objects; then you don't look into serialization, but into Java reflection.
But a word of warning there: reflections sounds easy, but be assured: there are many many ways for you to write slightly wrong code. And because reflection is basically a runtime thing, the java compiler doesn't help much. You write code that looks reasonable, it compiles, you run it, and you get exceptions throw at you.
In that sense, reflection is an advanced topic in the Java curriculum; and I think you should rather step back and clarify with your teachers what exactly they expect from you.
Given your latest updates: then simply look into that tutorial about serialization (and forget about the reflection part). And to answer your question: yes, that sounds like a viable approach. Can't say more; as you are not sharing code so far.

In Android (or Java itself), is it possible to a class to inherit from a class referenced by name?

Times ago, I was looking for a way to start ServiceMode programmatically. The great obstacle was how to understand the parameters that the class must receive (in its case, it is the SECRET CODES). And off course, the device must be rooted.
It had demanded plenty of research but I finally figured out how to start a system activity through command line. Now I want to create a class that extends from it. However, I don't have its API reference because it is hidded in Android internals and only accessible through things like reflection. I have only its name: com.sec.android.app.servicemodeapp.ServiceModeApp.
So, I'm wondering if Android/Java API let me create a class declaration in the form of:
public class MyCustomSystemActivity extends Class.forName("com.sec.android.app.servicemodeapp.ServiceModeApp") { ... }
Of course, this sentence is not allowed.
Can someone give me a hint if it is possible in other ways? And if yes, how can I declare such thing?
No, this is not possible. In a compiled language such as Java, the compiler needs to know what members are inherited and what methods are overridden, and it can't do this if it doesn't know what class is being extended.

Instance of client implementation of abstract class in library code

I'm writing some kind of library. I have an abstract class there. Client-code needs to extend it to use some methods. May happens that user quits application and after he restarts it I need to restore reference to his concrette class. My idea was to save canonical name of user's class and then just make newInstance() for it. However for some reason it can't create the instance. I've made a test:
void foo(AbstractClass a) {
String classname = a.getClass().getCanonicalName();
System.out.println(classname); //Output: "com.test.clientcode.Main.ConcretteClass"
a = null; // here I lost my reference to ConcretteClass for example, so all I have is a classname
Class.forName(classname).newInstance(); //Throws exception: "java.lang.ClassNotFoundException: `com.test.clientcode.Main.ConcretteClass"
}
It's a method within library code. For argument a I give it an instance of concrette user class.
UPDATE: to make things easier: in my library I have a method like above, argument a is a reference to client's ConcretteClass as we see in the output of 2nd line. Then I lose my reference. How can I make a new instance of ConcretteClass if the only thing I know is ConcretteClass' canonical name?
Your approach won't work.
If you want to "restore" the instance you should do in other way instead of simply newInstance. this is one thing. I don't know your concrete requirement, so I cannot answer further on the "restore" part.
I said your approach won't work, because you said your are writing a "library", so I guess client code will import your class, that is, your abstract class is in client codes's classpath. however, the client class won't be in your classpath. that's why you got the classnotfound Ex.
same as if I extend a class from guava for example, how come in guava codes, it knows my class and create an instance of my class?

How does a class literal work? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a class literal in Java?
I was going through literals in the Java tutorial where I came across this sentence:
Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.
Which doesn't make any sense to me, even though I paid attention to all the other topics prior to this. Can anyone explain in simple language with examples or references?
Instances of the class java.lang.Class represent classes and interfaces in a running Java application. For each class in the application, there is an instance of Class. The SomeClass.class syntax is a way to get from SomeClass to the corresponding instance of Class.
A class literal is just a special type to use when you want to do something involving the class itself, rather than an instance.
Here's a short list of a few things I commonly use this for (not at all comprehensive, but you can get a good idea)
1.) Reflection, you want to instantiate something in run-time that you may not know (perhaps it was stored in a variable of type Class)
2.) You want to check if 2 objects are of the same related type, you can write something along the lines of: B.class.isAssignableFrom(a.getClass());
3.) You want to list all the methods, or public variables within a class, perhaps for documentation.
There are many other uses, but these are the main ones I find myself using in common practice.
Speaking simple language: that thing, which you call class literal is an object which fully describes some class: all its methods, all its fields, all its annotations, class's modifiers and so on. It is needed for creating new instances of that class in runtime.
Short example:
Class x = String.class;
System.out.println(x);
you can use x to create runtime instances of the class it points to or to test the class of an object against it.
It evaluates to be the class identifier of the reference or primitive type's wrapper class. The expression void.class evaluates to the class identifier of the Void class. Same thing with 'String.class'

coldfusion 9 working with java objects

I'm currently working with the jodatime Java library and running into issues when trying to use it within coldfusion.
I've downloaded the latest jodatime 2.1 release, put the jar file into a folder on my local drive and pointed my coldfusion administrator to look at that folder in the ColdFusion Class Path under the Java and JVM settings page.
For the most part it works. but there are times when i get things like this:
local.oTestZone = createObject('java','org.joda.time.DateTimeZone').init('Europe/London');
Which should match with this: Constructor however I get an error in coldfusion saying:
Unable to find a constructor for class org.joda.time.DateTimeZone that accepts parameters of type ( java.lang.String ).
It works perfectly fine when I do something like this though:
local.oToZone = createObject('java','org.joda.time.DateTimeZone').forID('Europe/London');
Which matches on: forID
Am I missing something with my java implementation?
The DateTimeZone(String id) constructor is marked protected (it took me 3 reads of the JavaDoc to spot that), so CF won't be able to invoke it.
It looks to me like JodaTime expects you to use one of the static methods to construct your instances, so your second example is probably the right way of doing it.
You are dealing with an Abstract Class and a Protected Constructor.
A Protected Constructor means that only a subclass or a class in the same Package can call that constructor. So even though you are supplying the correct parameter, the constructor isn't available to your code.
The ColdFusion documentation has these tidbits:
"Although the cfobject tag loads the class, it does not create an instance object. Only static methods and fields are accessible immediately after the call to cfobject."
This is why forID works; it's a static method.
"To have persistent access to an object, you must use the init function, because it returns a reference to an instance of the object, and cfobject does not."
This and the previous statement are why methods like getOffset wont work in this situation.
I'm not familiar enough with this to know if there's a class that you can instantiate that will give you access to the constructor, but hopefully someone else can chime in.

Categories