This question already has answers here:
Scala: Can I declare a public field that will not generate getters and setters when compiled?
(2 answers)
Closed 7 years ago.
I wonder if it is possible to declare a public field in a Scala class. Scala normally generates a private field for val and var body variables/constructor parameters and getters/setters with the appropriate visibility.
I would like to know if it is possible to declare a public Java class field in Scala, not a getter.
PS: Why would anyone need that? It may be useful e.g. for integration with Java frameworks relying on fields:
class MyTest extends JUnitSuite {
#Rule
val temporaryFolder = new TemporaryFilder()
// throws java.lang.Exception: The #Rule temporaryFolder must be public
}
This is in response to the P.S, someone else has already posted an answer to the main question.
Because the logic behind using getters in setters (in java, for instance) is to "future-proof" your code, so that if your private field "x" somewhere down the line needs logic every time you get/set it, then you will just modify the method call and won't break any existing code that calls it. Whereas if you had just public fields and the need for logic arose, you would have to create getters/setters and then would break existing code due to changing the contract of the class. So scala just does this automatically to remove boilerplate code.
Hope this helps!
Related
Hi, I am quite a bit confused, why main method can access private fields.
void main() {
A obj = A();
obj._b = 'a';
print(obj._b);
}
class A {
String _b;
}
output:- a
please see the screenshot that theres no error.
Unlike Java, Dart doesn’t have the keywords public, protected, and private.
There's no keyword or annotation so you can declare a field/function as private on class level, but you can declare a field/function as private member on lib scope.Read
So lets come to your question, your main method is able to access a field started with '_' because there are in the same package. Create a new file and move your class to that file, and you will not be able to access the private member.
So,
identifiers that start with an underscore (_) are visible only inside the library.
In dart _ (underscore) sign is encapsulating fields on namespace level, not class level. For class level encapsulation ( still not private but protected ) consider using #protected annotation for the fields or move your class to a separate file.
I think this is the answer of you question right #umar_baloch.
I use groovy and like the #Immutable annotation. The problem is, that this annotation does not only create constructors with the specified class fields, but also creates an empty constructor and allows the fields to partly stay null (or take a default value). I want to prevent this.
Example:
#Immutable class User { int age}
can be called like
User jasmin = new User(30)
println "I am ${jasmin.age} years old" // I am 30 years old
but also like
User james = new User() //Uhoh, I have no age
println "I am ${james.age} years old" // I am 0 years old - maybe not expected
My question is therefor: are there any annotations or other ways that prevent calling the empty constructor? Possibly throwing an exception when there is no age passed (or null passed for it) at runtime. Bonus points if I get eclipse IDE support so that an empty constructor call is complained by eclipse at compile time.
I did not find something like #NotNull for groovy, but for java i found different annotations as the ones in this question. Would using one of these a good idea? How to decide? Or is it better to write my own custom annotation - and can I get IDE help by doing that?
I agree with you; there should be an option in the #Immutable attribute to prevent the generation of the default constructor.
As far as a workaround, this probably isn't as elegant as you'd like, but I'm throwing this out there. If you create a mutable super type without a default constructor, you could extend it with an #Immutable version. For example:
import groovy.transform.*
class MutableUser {
int age
// defining an explicit constructor suppresses implicit no-args constructor
MutableUser(int age) {
this.age = age
}
}
#Immutable
#InheritConstructors
class User extends MutableUser {
}
User jasmin = new User() // results in java.lang.NoSuchMethodError
But overall, this seems like an unnecessary amount of boilerplate just to suppress a no-arg constructor.
I am very new to GWT.
I am using ext-gwt widgets.
I found many places in my office code containing like,
class A extends BaseModel{
private UserAccountDetailsDto userAccountDetailsDto = null;
//SETTER & GETTER IN BASEMODEL WAY
}
Also, the DTO reference is unused.
public class UserAccountDetailsDto implements Serializable{
private Long userId=null;
private String userName=null;
private String userAccount=null;
private String userPermissions=null;
//NORMAL SETTER & GETTER
}
Now, I am able to get the result from GWT Server side Code and things Work fine, but when I comment the DTO reference inside the class A, I am not getting any Result.
Please explain me the need of that.
Thanks
Well the problem is in implementation of GXT BaseModel and GWT-RPC serialization.
BaseModel is based around special GXT map, RpcMap. This map has defined special serialization rules, which let's avoid RPC type explosion, but as side effect, only some simple types stored in map will be serialized. E.g. you can put any type inside the map, but if you serialize/deserialize it, only values of type Integer, String ,Double,Byte, Float and Short (and arrays of this types) will be present. So the meaning behind putting reference to the DTO inside BaseModel, is to tell GWT-RPC that this type is also have to be serialized.
Detailed explanation
Basically GWT-RPC works like this:
When you define an interface for service, GWT-RPC analyzes all the classes used in parameters/ return type, to create serializers/deserializers. If you return something like Map<Object,Object> from your service, GWT-RPC will have to create a serializer for each class which implements Map and Serializable interfaces, but also it will generate serializers for each class which implements Serializable. In the end it is quite a bad situation, because the size of your compiled js file will be much biggger. This situation is called GWT-RPC type explosion.
So, in the BaseModel, all values are stored in RpcMap. And RpcMap has custom written serializer (RpcMap_CustomFieldSerializer you can see it's code if you interested how to create such things), so it doesn't cause the problem described above. But since it has custom serializer GWT dosn't know which custom class have been put inside RpcMap, and it doesn't generate serializers for them. So when you put some field into your BaseModel class, gwt knows that it might need to be able to serialize this class, so it will generate all the required stuff for this class.
Porting GXT2 Application code using BaseModel to GXT3 Model is uphill task. It would be more or less completely rewrite on model side with ModelProviders from GXT3 providing some flexibility. Any code that relies on Model's events, store, record etc are in for a rewrite.
This question already has answers here:
Compare equality between two objects in NUnit
(20 answers)
Closed 7 years ago.
Is there an assertion built into Nunit that checks all properties between 2 objects are the same, without me having to override Equals?
I'm currently using reflection to Assert each individual property for a pair of objects.
I don't believe there is.
Assert.AreEqual compares non-numeric types by Equals.
Assert.AreSame checks if they refer to the same object
You can write framework agnostic asserts using a library called Should. It also has a very nice fluent syntax which can be used if you like fluent interfaces. I had a blog post related to the same.
http://nileshgule.blogspot.com/2010/11/use-should-assertion-library-to-write.html
You can two objects and there properties with ShouldBeEquivalentTo
dto.ShouldBeEquivalentTo(customer);
https://github.com/kbilsted/StatePrinter has been written specifically to dump object graphs to string representation with the aim of writing easy unit tests.
It comes witg Assert methods that output a properly escaped string easy copy-paste into the test to correct it.
It allows unittest to be automatically re-written
It integrates with all unit testing frameworks
Unlike JSON serialization, circular references are supported
You can easily filter, so only parts of types are dumped
Given
class A
{
public DateTime X;
public DateTime Y { get; set; }
public string Name;
}
You can in a type safe manner, and using auto-completion of visual studio include or exclude fields.
var printer = new Stateprinter();
printer.Configuration.Projectionharvester().Exclude<A>(x => x.X, x => x.Y);
var sut = new A { X = DateTime.Now, Name = "Charly" };
var expected = #"new A(){ Name = ""Charly""}";
printer.Assert.PrintIsSame(expected, sut);
GWT.create() is the reflection equivalent in GWT,
But it take only class literals, not fully qualified String for the Class name.
How do i dynamically create classes with Strings using GWT.create()?
Its not possible according to many GWT forum posts but how is it being done in frameworks like Rocket-GWT (http://code.google.com/p/rocket-gwt/wiki/Ioc) and Gwittir (http://code.google.com/p/gwittir/wiki/Introspection)
It is possible, albeit tricky. Here are the gory details:
If you only think as GWT as a straight Java to JS, it would not work. However, if you consider Generators - Special classes with your GWT compiler Compiles and Executes during compilation, it is possible. Thus, you can generate java source while even compiling.
I had this need today - Our system deals with Dynamic resources off a Service, ending into a String and a need for a class. Here is the solutuion I've came up with - btw, it works under hosted, IE and Firefox.
Create a GWT Module declaring:
A source path
A Generator (which should be kept OUTSIDE the package of the GWT Module source path)
An interface replacement (it will inject the Generated class instead of the interface)
Inside that package, create a Marker interface (i call that Constructable). The Generator will lookup for that Marker
Create a base abstract class to hold that factory. I do this in order to ease on the generated source code
Declare that module inheriting on your Application.gwt.xml
Some notes:
Key to understanding is around the concept of generators;
In order to ease, the Abstract base class came in handy.
Also, understand that there is name mandling into the generated .js source and even the generated Java source
Remember the Generator outputs java files
GWT.create needs some reference to the .class file. Your generator output might do that, as long as it is referenced somehow from your application (check Application.gwt.xml inherits your module, which also replaces an interface with the generator your Application.gwt.xml declares)
Wrap the GWT.create call inside a factory method/singleton, and also under GWT.isClient()
It is a very good idea to also wrap your code-class-loading-calls around a GWT.runAsync, as it might need to trigger a module load. This is VERY important.
I hope to post the source code soon. Cross your fingers. :)
Brian,
The problem is GWT.create doen't know how to pick up the right implementation for your abstract class
I had the similar problem with the new GWT MVP coding style
( see GWT MVP documentation )
When I called:
ClientFactory clientFactory = GWT.create(ClientFactory.class);
I was getting the same error:
Deferred binding result type 'com.test.mywebapp.client.ClientFactory' should not be abstract
All I had to do was to go add the following lines to my MyWebapp.gwt.xml file:
<!-- Use ClientFactoryImpl by default -->
<replace-with class="com.test.mywebapp.client.ClientFactoryImpl">
<when-type-is class="com.test.mywebapp.client.ClientFactory"/>
</replace-with>
Then it works like a charm
I ran into this today and figured out a solution. The questioner is essentially wanting to write a method such as:
public <T extends MyInterface> T create(Class<T> clz) {
return (T)GWT.create(clz);
}
Here MyInterface is simply a marker interface to define the range of classes I want to be able to dynamically generate. If you try to code the above, you will get an error. The trick is to define an "instantiator" such as:
public interface Instantiator {
public <T extends MyInterface> T create(Class<T> clz);
}
Now define a GWT deferred binding generator that returns an instance of the above. In the generator, query the TypeOracle to get all types of MyInterface and generate implementations for them just as you would for any other type:
e.g:
public class InstantiatorGenerator extends Generator {
public String generate(...) {
TypeOracle typeOracle = context.getTypeOracle();
JClassType myTYpe= typeOracle.findType(MyInterface.class.getName());
JClassType[] types = typeOracle.getTypes();
List<JClassType> myInterfaceTypes = Collections.createArrayList();
// Collect all my interface types.
for (JClassType type : types) {
if (type.isInterface() != null && type.isAssignableTo(myType)
&& type.equals(myType) == false) {
myInterfaceTypes.add(type);
}
for (JClassType nestedType : type.getNestedTypes()) {
if (nestedType.isInterface() != null && nestedType.isAssignableTo(myType)
&& nestedType.equals(myTYpe) == false) {
myInterfaceTypes.add(nestedType);
}
}
}
for (JClassType jClassType : myInterfaceTypes) {
MyInterfaceGenerator generator = new MyInterfaceGenerator();
generator.generate(logger, context, jClassType.getQualifiedSourceName());
}
}
// Other instantiator generation code for if () else if () .. constructs as
// explained below.
}
The MyIntefaceGenerator class is just like any other deferred binding generator. Except you call it directly within the above generator instead of via GWT.create. Once the generation of all known sub-types of MyInterface is done (when generating sub-types of MyInterface in the generator, make sure to make the classname have a unique pattern, such as MyInterface.class.getName() + "_MySpecialImpl"), simply create the Instantiator by again iterating through all known subtypes of MyInterface and creating a bunch of
if (clz.getName().equals(MySpecialDerivativeOfMyInterface)) { return (T) new MySpecialDerivativeOfMyInterface_MySpecialImpl();}
style of code. Lastly throw an exception so you can return a value in all cases.
Now where you'd call GWT.create(clz); instead do the following:
private static final Instantiator instantiator = GWT.create(Instantiator.class);
...
return instantiator.create(clz);
Also note that in your GWT module xml, you'll only define a generator for Instantiator, not for MyInterface generators:
<generate-with class="package.rebind.InstantiatorGenerator">
<when-type-assignable class="package.impl.Instantiator" />
</generate-with>
Bingo!
What exactly is the question - i am guessing you wish to pass parameters in addition to the class literal to a generator.
As you probably already know the class literal passed to GWT.create() is mostly a selector so that GWT can pick and execute a generator which in the end spits out a class. The easist way to pass a parameter to the generator is to use annotations in an interface and pass the interface.class to GWT.create(). Note of course the interface/class must extend the class literal passed into GWT.create().
class Selector{
}
#Annotation("string parameter...")
class WithParameter extends Selector{}
Selector instance = GWT.create( WithParameter.class )
Everything is possible..although may be difficult or even useless. As Jan has mentioned you should use a generator to do that. Basically you can create your interface the generator code which takes that interface and compile at creation time and gives you back the instance. An example could be:
//A marker interface
public interface Instantiable {
}
//What you will put in GWT.create
public interface ReflectionService {
public Instantiable newInstance(String className);
}
//gwt.xml, basically when GWT.create finds reflectionservice, use reflection generator
<generate-with class="...ReflectionGenerator" >
<when-type-assignable class="...ReflectionService" />
</generate-with>
//In not a client package
public class ReflectionGenerator extends Generator{
...
}
//A class you may instantiate
public class foo implements Instantiable{
}
//And in this way
ReflectionService service = GWT.create(ReflectionService.class);
service.newInstance("foo");
All you need to know is how to do the generator. I may tell you that at the end what you do in the generator is to create Java code in this fashion:
if ("clase1".equals(className)) return new clase1();
else if ("clase2".equals(className)) return new clase2();
...
At the final I thought, common I can do that by hand in a kind of InstanceFactory...
Best Regards
I was able to do what I think you're trying to do which is load a class and bind it to an event dynamically; I used a Generator to dynamically link the class to the event. I don't recommend it but here's an example if it helps:
http://francisshanahan.com/index.php/2010/a-simple-gwt-generator-example/
Not having looked through the code of rocket/gwittir (which you ought to do if you want to find out how they did it, it is opensource after all), i can only guess that they employ deferred binding in such a way that during compile time, they work out all calls to reflection, and statically generate all the code required to implement those call. So during run-time, you cant do different ones.
What you're trying to do is not possible in GWT.
While GWT does a good job of emulating Java at compile time the runtime is of course completely different. Most reflection is unsupported and it is not possible to generate or dynamically load classes at runtime.
I had a brief look into code for Gwittir and I think they are doing their "reflection stuff" at compile time. Here: http://code.google.com/p/gwittir/source/browse/trunk/gwittir-core/src/main/java/com/totsp/gwittir/rebind/beans/IntrospectorGenerator.java
You might be able to avoid the whole issue by doing it on the server side. Say with a service
witch takes String and returns some sort of a serializable super type.
On the server side you can do
return (MySerializableType)Class.forName("className").newInstance();
Depending on your circumstances it might not be a big performance bottleneck.