I'm currently learning java in order to make an app on android and I checked that swift has a structure that stores information in memory. I'd like to know, if in java this type of object exists, because the class storage the reference on the memory. Also I checked that Kotlin has a data class, does java have a similar object?
No, there is nothing like that, but there are tools, that try to mimic this behavior, for example lombok. Using #Data annotation we're getting default constructor, getters, setters, toString, equals, hashCode. We can fine-tune it by using annotations like #Getter, #NoArgsConstructor etc.
Neither Java nor Kotlin have anything similar to those Swift types you are talking about. Assignment always copies references to an object, rather than the object itself. What Kotlin's data classes do is that they create a copy method (among other things) that allows you to explicitly make a copy of an object, but you still have to actually call the method.
val b = a // b and a point to the same object, even if it is a data class
val b = a.copy() // this is what you need to do to create a copy of a data class
Java assignment copies references, not objects, and the same is true for Kotlin. There is no way around this, because it is a feature of the language itself. Copy constructors and methods (like what Kotlin's data class gives you) are the closest thing you have to such a feature. To get something like this in Java without having to manually write the code everytime, you could look into Project Lombok.
Starting with Java 14 you will have access to Record immutable class. It is similar in concept to data class in Kotlin.
Related
Sorry if this is very specific...
I am looking at Javapoet's implementation of AnnotationSpec.get(Annotation). It recursively clones an annotation so that you can copy it to another element. In my case, I am trying to copy an #OpenApi annotation from one method to another.
The issue is caused by the annotations being written in kotlin. Anywhere the annotation needs a class, it is using KClass<*>. Javapoet only handles Java types, like Class<?>. From Java, I can say if (o instanceof Class || o instance of KClass) no problem.
However, there's also code that says o.getClass().isArray() but, from what I can tell, kotlin annotations use Array<*> for arrays, so that check is failing. The actual type appears to be com.sun.proxy.$Proxy54 when I inspect it, but I have no idea what that is.
How do you detect if an object is an kotlin array from Java? Can this be converted to a Java array? Is there some universal way to make kotlin annotations appear as java annotations using Class and built-in arrays and so on?
Kotlin arrays and Java arrays are the same thing at the VM level. Array<*> is Kotlin's syntax for arrays, but the objects are the same thing. .isArray should work.
The proxy objects are typical for what you get when you call getClass on annotation objects in Java or Kotlin. You likely need to use annotationType instead of getClass.
Id like to convert an existing kotlin/java set, to scala immutable set, using kotlin/java code.
scala.collection.JavaConversions.asScalaSet only gives me the mutable set.
Must do it that way, because I am inheriting from a scala class on another repo, and would not like to insert scala packages and plugins to my project.
A simple answer would be: you cannot. Java/Kotlin collections are inherently mutable, while Scala immutable collections have a completely different implementation on the inside, so they are not allowed to be freely converted from one to the other.
Now you have two options: first, you can use a more generic interface (scala.collection.Set for example), or, second, you can create a new immutable Scala collection and put all the elements into it: scala.collection.immutable.HashSet().concat(yourExistingCollection)
I am trying to create a Java wrapper for my C++ library using SWIG.
In order to get all the features I need within a Java programming environment, I need directors.
More specifically, I need Java users to be able to inherit from my C++ classes and implement certain methods.
In particular, one of the method that needs to be implemented is some sort of clone() method.
In C++, the user implementation provides an object pointer Base*. This pointer is then managed by the library itself.
Base* Derived::clone() {
return new Derived(*this);
}
The problem I have with the Java wrapper is that the Java proxy class for Base acquires the management of the corresponding C++ director class SwigDirector_Base, by default.
This is certainly suitable in the general case, but not in this particular user-defined clone() function.
My personal constraint is that the Java wrapper for my C++ library uses no Java-specific code, so the user implementation should look like:
class Derived {
...
Base clone() {
return new Derived(this);
}
}
So far, to make it work and avoid garbage collection of the copied Java instance, I have used the trick mentioned in http://www.swig.org/Doc2.0/SWIGDocumentation.html#CSharp_memory_management_member_variables.
And to make sure that the Java Derived class never deletes the corresponding C++ director class SwigDirector_Base, I have used %typemap(directorout) to set the value of the Java cMemOwn flag of the copied instance from the C++ wrapper code, that is in method SwigDirector_Base::clone().
I am not so happy with this solution as it applies to all methods returning a pointer to the Base class, whether it is a copy method or not...
Any idea on how to do this on a function-specific way? Or in any other way?
Out of curiosity, I'd like to know if any class exists in Java with a method that returns a copy of its data structure. I ask because in class the teacher said a method like this breaks privacy, but I think that getting a copy of the structure is useful if you want to rearrange the structure. I'd like an example. Thanks.
I'm not entirely sure what you mean by the "data structure" of a class, but assuming you mean the members it contains, what you're looking for is reflection.
Try this tutorial.
Maybe you are missing the point: If you build a class which encapsulates some kind of internal data then you should NOT add a method which returns the internal data structure, but only the data that is encapsulated.
(Which is kind of the idea of encapsulation)
There should not be any need to "rearrange" your internal representation from the outside - because it is supposed to be internal and thus transparent in its use. (Meaning: You should not even be able to say what kind of data structure is used)
If you serialize it, any object (that is serializable) will happily prints its internal structure to a binary stream. And yes, this breaks encapsulation.
And yes, no one stops you from going to change the binary output and read it in again to create an altered object.
NB: there are more strange issues regarding serialization. For example, when deserializing objects new objects are created without their constructor ever being called. Et cetera. Serialization of objects is the maybe least object-oriented thing one can do with objects.
You're mixing up some concepts here.
Classes really are "data structures + methods", so in general you'd need a class to represent your class. Hey, a nice custom-built one would be the class your data is already in. You may be thinking of a class as a collection of simple fields, but this is not always the case.
As others have mentioned, you can extract the data via reflection, e.g.
public Map<String,Object> fields() {
Map output=new hashMap<String,Object>();
for (Field f:getClass().getFields())
{
try{
output.put(f.getName(), f.get(this));
}
catch(... //IllegalArgument, IllegalAccess.. {... }
}
return output;
}
You can get into encapsulation issues here, in general the class should provide the data that you need to see from it, I tend to use things like this only for debugging.
I'm not sure what you mean by "rearrange the structure". The class generally represents the structure of the data. If there's a transformation you want to accomplish, it probably belongs in a class method, e.g. are you thinking of something like a co-ordinates class that can provide a transformed version of itself into polar co-ordinates?
A simple way to see the internal representation of an object is to serialise it using XStream. This will generate an XML representation of the class and its components (and so on).
Does this break encapsulation ? Yes - in the sense that you're able to inspect the internal structure of the class. You can take that XML, change it, and provided that it matches the .class structure that it came from, deserialise it back into a .class instance.
Suppose, I have a lot of classes, which are constructed using Java reflection (for some reason). Now I need to post-inject values to fields, which are
annotated with #PostInject.
public class SomeClass {
#PostInject
private final String someString = null;
public void someMethod() {
// here, someString has a value.
}
}
My question is: what is a fast way to set a field using reflection?
Remember, I need to do this very often on a lot of classes, that's
why performance is relevant.
What I would do by intuition is shown by this pseudo-code:
get all fields of the class
clazz.getFields();
check, which are annotated with #PostInject
eachField.getAnnotation(PostInject.class);
make these fields accessible
eachAnnotatedField.setAccessible(true);
set them to a certain value
eachAnnotatedField.set(clazz, someValue);
I'm afraid that getting all fields is the slowest thing to do.
Can I someone get a field, when I know it from the beginning?
NOTE: I can't just let the classes implement some interface, which would
allow to set the fields using a method. I need POJOs.
NOTE2: Why I want post-field injection: From the point of view of an API user, it must be possible to use final fields. Furthermore, when the types and number of fields are not known by the API a priori, it is impossible to achieve field initialization using an interface.
NOTE2b: From the point of view of the user, the final contract is not broken. It stays final. First, a field gets initialized, then it can't be changed. By the way: there are a lot of APIs which use this concept, one of them is JAXB (part of the JDK).
How about doing steps 1 to 3 just after you constructed the object and saving the set of annotated fields that you obtain either in the object itself or by keeping a separate map of class to set-of-annotated-fields?
Then, when you need to update the injected fields in an object, retrieve the set from either the object or the seperate map and perform step 4.
Don't know if it's any good, but this project looks like it would do what you want. Quote:
A set of reflection utilities and
miscellaneous utilities related to
working with classes and their fields
with no dependencies which is
compatible with java 1.5 and generics.
The utilities cache reflection data
for high performance operation but
uses weak/soft caching to avoid
holding open ClassLoaders and causing
the caches to exist in memory
permanently. The ability to override
the caching mechanism with your own is
supported.
Another option, as you say you know the few fields concerned from the beginning, is to ask only for those fields or methods.
Example : see getDeclaredMethod or getDeclaredField in java/lang/Class.html
You can exploit existing frameworks that allow to inject dependencies on object construction. For example Spring allows to do that with aspectj weaving. The general idea is that you define bean dependencies at spring level and just mark target classes in order to advise their object creation. Actual dependency resolution logic is injected directly to the class byte-code (it's possible to use either compile- or load-time weaving).
Fastest way to do anything with reflection is to cache the actual Reflection API classes whenever possible. For example I very recently made a yet-another-dynamic-POJO-manipulator which I believe is one of those things everyone ends up doing at some point which enables me to do this:
Object o = ...
BeanPropertyController c = BeanPropertyController.of(o);
for (String propertyName : c.getPropertyNames()) {
if (c.access(propertyName) == null &&
c.typeOf(propertyName).equals(String.class)) {
c.mutate(propertyName, "");
}
}
The way it works is that it basically has that one controller object which lazyloads all the properties of the bean (note: some magic involved) and then reuses them as long as the actual controller object is alive. All I can say is that by just saving the Method objects themselves I managed to turn that thing into a damn fast thing and I'm quite proud of it and even considering releasing it assuming I can manage to sort out copyrights etc.