I'm pretty new to java, and on the java tutorial it uses the terms "class literal" and "reflection".
From the reflection api trail from the java website, http://docs.oracle.com/javase/tutorial/reflect/index.html, it says
Extensibility Features
An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
What does that mean?
Thanks.
A class literal is something like String.class, i.e. a compile-time literal representing the String class.
In short, reflection is a language feature that allows you to "reflect" on the code, i.e. you can query the system for classes, methods, fields, etc. and use that data to create new instances, call methods or change the value of fields.
Reflection might be useful to create objects of classes that are not known at compile-time, but are on the classpath at runtime. Several extension frameworks make use of that, mostly by providing fully qualified class names in some text file (e.g. com.acme.SomeFancyClass), getting the associated Class object from the class loader and creating new instances.
Other frameworks (e.g. Apache Common's builder objects, OGNL, Java Beans etc.) use reflection to query the available properties (getters and/or matching setters) that can be accessed (through calls to those getters/setters).
However, if you are new to Java, I'd recommend diving into other language features before loosing yourself in the depth of the reflection facility.
Related
I am a Java programmer using Ruby for the first time, and I have a few questions about how some features compare between the two languages.
Is the notion of a constructor relevant in Ruby? If yes, how does the behavior compare to Java constructors?
In Java, we generally keep separate .java files for different classes (when not nested). Is there a similar practice in Ruby? Or is each class itself not as important as in Java?
How do you extend a class (or .rb file)? I would like to extend a class and call super inside my local constructor to initialize some items.
How do you access the methods of a class in a .rb file, from a different class in another .rb file?
Are Ruby "gems" equivalent to Java packages?
1) Yes. There is concept of constructor which behaves like Java one. However, the constructor method is called initialize in Ruby, when in Java, the constructor has the same name as of class itself. eg:
class Foo
def initialize
# initialization logic here
end
end
2) Yes, it's rathe considered a best practice to store classes per file - separately, but it is not constrained by language.
3) For inheritance, there is different syntax in Ruby. Please consider following code:
class Parent
end
class Child < Parent
end
4) It is actually quite similar to Java, you use . to indicate method on object:
class Person
def name
"Tester"
end
end
p = Person.new
puts p.name
5) There is not really concept of packages in Ruby, but you might use modules to namespace your classes, eg:
module Foo1
class Biz
end
end
module Foo2
class Biz
end
end
b1 = Foo1::Biz.new
b2 = Foo2::Biz.new
Yes. No big difference.
Yes. More freedom in ruby though. (If you want to you can even define the same class in several files....) Apart from classes there are also modules that can be used as mixin - a sort of multiple inheritance.
The < operator is used for inheriting another class. It is the extends of ruby. In the subclass constructor you can call super just like in Java.
Instance methods are accessed just like in Ruby with a dot. Class methods can be accessed as in Java with a dot after the class name. Or with a double colon.
No. Ruby has no packages. Often modules are used around classes to provide a namespace in order to avoid clashes. Gems in ruby are more like a jar file (a maven dependency for example) in java.
Is constructor a relevant thing in Ruby? If yes, any change in behavior compared to Java?
No, there are no constructors in Ruby. Unlike Java, which has three different kinds of "methods" (instance methods, static methods, and constructors), Ruby has exactly one kind of methods: instance methods.
In Java, we generally keep separate .java files for different classes(if not nested). Is the approach same in Ruby?
No. You would use one file for related concepts. It might be a single class, but then again, it might not. For example, the set.rb file in the Ruby standard library contains both the Set and the SortedSet class.
It might also be that a single class is defined in multiple files. For example, the above-mentioned set.rb not only contains the Set and SortedSet class, it also contains a fragment of the Array class which has a to_set method for turning an array into a set.
Or Class itself is not much relevant?
Ruby is a class-based OO language, classes are very much relevant.
How can i extend one class (or a .rb file)? I would like to extend one class and call the super constructor inside my local constructor to initialize some items.
You can't "extend a file". You can, however extend classes, just like in Java.
How to access the Methods inside a class (.rb file) from another class (.rb file)?
Again, files have nothing to do with this.
You call methods on objects, just like in pretty much every other OO language, including Java. You don't "access methods inside a class".
Is packages in Java and Gems in Ruby are the same thing? We used to have multiple packages in a project for tests, utilities etc.Is the approach same in Ruby as well?
No. Gems are more like Maven artefacts. There is no analog to a Java package in Ruby, although one might use modules that way.
What are the caveats that a developer should be aware of while writing reflective code that works both with Java and Kotlin?
For example, I have an existing library that uses reflection and it works well with Java. However, when I use the same with Kotlin, my reflective code doesn't seem to pick up the annotations on fields.
Here are some of the differences that I noticed.
1. Acquiring a Class instance
// Example 1.1 - Java
Class<?> userClass = User.class; // From a class name
userClass = userInstance.getClass(); // OR from an instance
Getting a Java class instance in Kotlin
// Example 1.2 - Kotlin
val userClass = userInstance.javaClass // From an instance
I'm unable to use the .class facility or the .getClass() method in Kotlin as we do in Java.
2. Delegates
When I use delegated properties in a Kotlin class, the properties that I retrieve have the $delegate suffix. This is a bit contrary to the fields that we get in Java (I do understand Kotlin does not have fields, only properties). How does this affect meta-programming?
However, with delegates I see that most of the methods retain their behavior as they do in Java. Are there any other differences that I have to be aware of?
Making Java and Kotlin interoperable for me would require understanding about 1 discussed above, plus other limitations / differences that Kotlin brings to meta-programming.
For example, I have an existing library that uses reflection and it works well with Java. However, when I use the same with Kotlin, my reflective code doesn't seem to pick up the annotations on fields.
Can it be because the fields are private now?
Anyway, there are issues with annotations on fields at the moment, this will be fixed in on of the upcoming milestones.
Some other relevant issues:
https://youtrack.jetbrains.com/issue/KT-5967
https://youtrack.jetbrains.com/issue/KT-4169
https://youtrack.jetbrains.com/issue/KT-3625
I'm unable to use the .class facility or the .getClass() method in Kotlin as we do in Java.
Only the syntax is different: javaClass<C>() works exactly the same as C.class, and x.javaClass does the same thing as x.getClass()
When I use delegated properties in a Kotlin class, the properties that I retrieve have the $delegate suffix.
Minor correction: the fields have the $delegate suffix, not the properties.
However, with delegates I see that most of the methods retain their behavior as they do in Java. Are there any other differences that I have to be aware of?
The docs here give you a detailed description of how delegated properties are implemented.
Making Java and Kotlin interoperable for me would require understanding about 1 discussed above, plus other limitations / differences that Kotlin brings to meta-programming.
The more your Kotlin code resembles Java code, the smaller is the difference from the reflection point of view. If you write idiomatic Kotlin, e.g. use default parameter values, traits, properties, delegates, top-level functions, extensions etc, the classes you get differ from idiomatic Java, otherwise they are closely aligned.
Please provide some basic information of how TypeLiteral in Google Guice or Java EE is used, It will be very helpful if it would be explained using a simple code, thanks in advance
The purpose of TypeLiteral in Guice is to allow you to bind classes and instances to generic types (with type parameters specified) avoiding the problems stemming from the fact that generics are not reified in Java, i.e. from the fact that erasure hides the difference between SomeInterface<String> and SomeInterface<Integer> at runtime. TypeLiteral allows the value of a generic parameter survive erasure by creating an ad hoc subclass of the generic type.
Example usage of TypeLiteral:
bind(new TypeLiteral<SomeInterface<String>>(){})
.to(SomeImplementation.class);
This binds a parameter of type SomeInterface<String> to SomeImplementation class.
For some background information have a look at this blog post on super type tokens and then this one on type literals.
Like anything in Guice - modularity, reusability, and removal of boilerplate are core concepts of all utilities.
Of course, anything you do in Guice can be mimicked in Java - at the cost of lots of boilerplate So... the real question is :
How can we USE TypeLiterals to write more modular/reusable components ?
The power of TypeLiterals in Guice is that it allows you to refernce implementations of a service without defining what that service is.
Lets start with a simple list in a program where we have many types of lists that are processed differntly :
List<String> myStringList = new ArrayList<String>();
Now, how should I process these Strings ? At runtime, there is no way to "know" that its a String list. So, often times I might create a factory, like so , that gets processing objects for me :
ProcessorFactory.get(String.class).process(myStringList);
Thus, I might use a factory (with a bunch of if/else or case statements) to define processors for different data types. My constructor, for the object which uses these processors, and which needs access to various Processor Implementations, might look like this :
public MyClass(Processor<String> strProcessor, Processor<Integer> intProcessor)P
{
//Simple enough, but alot of boiler plate is required to launch this constructor.
}
//and to invoke
new MyClass(PRocessorFactory.get(....), ProcessorFactory.get(...));
All good so far... Until we realize that there is a better way :
In the Guice world, I can forget about writing this factory - rather, I can explicitly BIND classes to processors. The advantage of this is that there are no static dependencies - the class which needs to USE processor implementations DOES NOT need any static dependency on a factory -rather, the classes are directly injected. Thus, I can easily define a class which uses complex dependencies, without having to build a factory aware class builder... Thus, I have far less boilerplate :
#Inject
public MyClass(Processor<String> implStr, Processor<Integer> implInt)
{
//Now , this method will work magically, because Guice is capable of
//Using the loaded modules, which define bindings between generics and their implementations
}
//Elsewhere I simply define a single guice module that does the binding, and make sure to load it before my application launches.
There is a good tutorial on this with interface implementations and binding examples, here : http://thejavablog.wordpress.com/2008/11/17/how-to-inject-a-generic-interface-using-guice/
This is a way how guys bypass generics erasure in java. You need it, when you want ot bind some implementation to parametrized(generic) interface. Found some usage in Guice docs:
bind(new TypeLiteral<PaymentService<CreditCard>>() {})
.to(CreditCardPaymentService.class);
This admittedly odd construct is the way to bind a parameterized type. It tells Guice how to honor an injection request for an element of type PaymentService. The class CreditCardPaymentService must implement the PaymentService interface. Guice cannot currently bind or inject a generic type, such as Set; all type parameters must be fully specified.
The TypeLiteral class is a workaround for the fact that you cannot have class literals for generic types. The API doc of Binder (this is from Google Guice, but the Java EE class of the same name has exactly the same purpose) gives an example for how it's used:
bind(new TypeLiteral<PaymentService<CreditCard>>() {})
.to(CreditCardPaymentService.class);
This specifies that any auto-injected reference of type PaymentService<CreditCard> will be implemented by the concrete class CreditCardPaymentService, leaving the option for PaymentService<Coupon> to be implemented by a different class. Without TypeLiteral, this would not be possible because the Java compiler will accept PaymentService<CreditCard>.class, only PaymentService.class.
Note that this also requires the use of anonymous subclasses (the {} after new TypeLiteral<PaymentService<CreditCard>>()) in order to work around type erasure.
I'll simplify the answer/reason for the existence of TypeLiteral<> in GUICE:
if java allows you to write:
bind(FooInterface<String>.class).to(FooImplementation.class);
then you are done, there is no need for TypeLiteral<>
but java has this "Type Erasure" thing for generics, so FooInterface<String>.class won't even get complied.
So you use:
bind(new TypeLiteral<FooInterface<String>>() {}).to(FooImplementation.class);
"new TypeLiteral<Interface>() {}" will create some anonymous class and new an object out of it. You can imagine that object knows everything about the tpye info of the Interface, so GUICE use that object to perform the DI magic.
I'm working with Java 6's annotation processing, i.e. what can be found within javax.annotation.processing (not Java 5's APT).
I wonder what the conceptional difference between the various Element, Type, and Mirror classes is. As I don't really understand this, it's hard to efficiently program an annotation processor. There are various methods that 'convert' between these notions but I'm not really sure what I'm doing when using them.
So, for example, let me have an instance of AnnotationMirror.
When I call getAnnotationType() I get an instance of DeclaredType (which implements TypeMirror for whatever reason).
Then I can call asElement() on this one and obtain an instance of Element.
What has happened?
There is indeed on overlap between these concepts.
Element models the static structure of the program, ie packages, classes, methods and variables. Just think of all you see in the package explorer of Eclipse.
Type models the statically defined type constraints of the program, ie types, generic type parameters, generic type wildcards. Just think of everything that is part of Java's type declarations.
Mirror is an alternative concept to reflection by Gilad Bracha and Dave Ungar initially developed for Self, a prototype-based Smalltalk dialect. The basic idea is to separate queries about the structure of code (and also runtime manipulation of the structure, alas not available in Java) from the domain objects. So to query an object about its methods, instead of calling #getClass you would ask the system for a mirror through which you can see the reflection of the object. Thanks to that separation you can also mirror on classes that are not loaded (as is the case during annotation processing) or even classes in a remote image. For example V8 (Google's Javascript engine) uses mirrors for debugging Javascript code that runs in another object space.
This paper may help understanding the design of Java 6 annotation processing:
Gilad Bracha and David Ungar. Mirrors:
Design Principles for Meta-level
Facilities of Object-Oriented
Programming Languages. In Proc. of
the ACM Conf. on Object-Oriented
Programming, Systems, Languages and
Applications, October 2004.
The object of type javax.lang.model.element.AnnotationMirror represents an annotation in your code.
The declared type represents the annotation class.
Its element is the generic class (see http://java.sun.com/javase/6/docs/api/javax/lang/model/element/TypeElement.html for more information on that matter). The element might be the generic version of a class, like List, where as the declared type is the parametrized version, for instance List<String>. However I'm not sure it is possible to have annotations classes use generics and thus the distinction might be irrelevant in that context.
For instance lets say you have the following JUnit4 method:
#Test(expected = MyException.class)
public void myTest() {
// do some tests on some class...
}
The AnnotationMirror represents #Test(expected = NullPointerException.class). The declared type is the org.junit.Test class. The element is more or less the same as there are no generics involved.
I've been writing .NET software for years but have started to dabble a bit in Java. While the syntax is similar the methodology is often different so I'm asking for a bit of help in these concept translations.
Properties
I know that properties are simply abstracted get_/set_ methods - the same in C#. But, what are the commonly accepted naming conventions? Do you use 'get_' with an underscode or just 'get' by itself.
Constructors
In C# the base constructor is called automatically. Is this also true in Java?
Events
Like properties, events in .NET are abstracted add_/remove_/fire_ methods that work on a Delegate object. Is there an equivalent in Java? If I want to use some sort of subscriber pattern do you simply define an interface with an Invoke/Run method and collect objects or is there some built-in support for this pattern?
Update: One more map:
String Formatting
Is there an equivalent to String.Format?
Java from a C# developer's perspective
Dare Obasanjo has updated his original 10 year old article with a version 2:
C# from a Java Developer's Perspective v2.0
Although for you its the other way round :)
To answer your specific questions:
Properties
By convention, Java uses "get" or "set" followed by the variable name in upper camel case. For example, "getUserIdentifier()". booleans often will use "is" instead of "get"
Constructors
In Java, superclass constructors are called first, descending down the type hierarchy.
Events
By convention (this is the one you'll get the least agreement on...different libraries do it slightly differently), Java uses methods named like "addEventTypeListener(EventTypeListener listener)" and "removeEventTypeListener(EventTypeListener listener)", where EventType is a semantic name for the type of event (like MouseClick for addMouseClickListener) and EventTypeListener is an interface (usually top-level) that defines the methods available on the receivers - obviously one or more of those references is essentially a "fire" method.
Additionally, there is usually an Event class defined (for example, "MouseClickEvent"). This event class contains the data about the event (perhaps x,y coordinates, etc) and is usually an argument to the "fire" methods.
Wikipedia has a nice in depth comparison here: http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Java
A bean property in java is preceeded by a get followed by the bean name starting with a capital letter. For instance the property 'color' would be associated with the methods 'getColor()' and 'setColor(int color)' (assuming the property is of type int). There is a special case for boolean properties, the getter will be called 'is'... as in 'isWhite()', 'isBlack()'. The setter remains the same.
When a class is created in java, all its parent class constructors are called in order, parents before children.
Events in Java are specific to a given event model, and not a core part of the language. Examine the documentation for Swing or SWT for information on the event models of those GUI toolkits.
Sun's Code Conventions are a great reference for the Java way of doing and naming things.
Property getters and setters can go by whichever naming convention you desire, or that your organization has standardized. A good naming convention is simply one that is common among those who will use/see it. That said, most in the Java community use 'getSomething/setSomething' as the naming convention on getters and setters.
Base constructors are called automatically, just like C#.