Java equivalent of Javascript prototype - java

In JavaScript, you can do this.
String.prototype.removeNumericalCharacters = function(){
...code...
}
or
Number.prototype.addTwo = function(){
...code...
}
var a = 5;
a.addTwo();
//a is now 7
Is there a way to do something similar in Java? (I don't mean the actual function, just using that as an example)
An example in Java would be
int a = 5;
a.addTwo();
//A is now 7
My question is how do I define the .addTwo() method.

It's Friday so lets answer this question. I'm not going to dive into much details (it's Friday!) but hopefully you'll find this useful (to some extend).
You certainly know that Java objects don't have prototypes. If you want to add a field or a method to a Java class you have two options. You either extend the existing class and add the method/ field to it like this:
public class A {
}
public class B extends A {
int addTwo () {...};
}
However that's not changing the parent class. Objects of class A in the example still have no method addTwo.
Second approach is to dynamically change the class (you could use things like javassist) and method/fields to it. It's all fine but to use these new methids/fields you'd have to use reflection. Java is strongly typed and needs to know about class's available methods and fields during the compile time.
Finally and that's when things get really rough - primitive types, in your instance int, are 'hardwired' into JVM and can't be changed. So your example
int a = 5;
a.addTwo();
is impossible in Java. You'd have more luck with dynamic languages on JVM (Groovy is one of them). They're usually support optional typing and allow dynamic method calls.
So enjoy Friday!

Related

How can I initialize interdependent final references?

I have a class and a factory function that creates new anonymous class objects extending that class. However, the anonymous class objects all have a method in which there are references to other objects. In my full program, I need this to create and combine parsers, but I've stripped down the code here.
class Base{
public Base run(){
return null;
}
static Base factory(final Base n){
return new Base(){
public Base run(){
return n;
}
};
}
}
public class CircularReferences{
public static void main(String args[]){
final Base a, b;
a = Base.factory(b);
b = Base.factory(a);
}
}
I get CircularReferences.java:17; error: variable b might not have been initialized. That's true, it wasn't, but can't I set aside space for these variables and then initialize them using references to these spaces, which will be filled with the proper values before they are ever actually used? Can I perhaps use new separately from the constructor? How can I create these variables so they reference each other?
The quick answer is that you can't do this. If you absolutely must do something like this, then use a private setter on the class and bind things together after they are constructed (i.e. use enforced immutability instead of final fields). Hopefully it's obvious that I don't think this is a good idea - I just wanted to provide a answer to your actual question before I answer the way that I really want to.
OK - now that is out of the way, here's the real response that is called for here:
Generally speaking, this sort of situation is a strong indicator that refactoring is needed to separate concerns. In other words, the Base class is probably trying to be responsible for too many things.
I realize that the example is contrived, but think about what functionality requires the circular dependency, then factor that functionality out into a separate class/object that then gets passed to both of the Base constructors.
In complex architectures, circular dependency chains can get pretty big, but strictly forcing final fields is great way to look for those types of refactoring opportunities.
If you have a concrete example, I'd be happy to help with some refactoring suggestions to break a dependency like this.
concrete example provided - here's my suggestion:
It seems like there is a concern of obtaining an appropriate ParseStrategy based on a token. A ParseStrategyProvider. So there would be a TopLevelParseStrategy that reads the next token, looks up the appropriate parse strategy, and executes it.
TopLevelParseStrategy would hold a final reference to the ParseStrategyProvider.
The ParseStrategyProvider would then need to have a registration method (i.e. registerStrategy(token, parseStrategy) ).
This isn't functionally much different from doing this with enforced immutability via a private setter (the registerStrategy method is for all intents and purposes the same as the private setter), but the design is much more extensible.
So you'd have:
public ParseStrategy createParser(){
ParseStrategyProvider provider = ParseStrategyProvider.create();
TopLevelParseStrategy topLevel = new TopLevelParseStrategy(provider);
provider.registerStrategy("(", topLevel);
// create and register all of your other parse strategies
return topLevel;
}

Generate A Java Class From A Java Application

I am trying to create a data validation program that checks if a specific data type is valid by running each "type" (eg. name, age, gender) through its own validation method (each method is unique to its data type), the only problem is I want the application to be flexible to different data types and different amounts of data types.
Is there a way I can actually generate an entirely new Java application with methods for each type from the running Java application (for example "writing" a new class) during runtime once I have all the types?
Example Code:
public class JavaGen(){
public static void main(String[] args){
int dataLength = Integer.parseInt(JOptionPane.showInputDialog("Amount Of Data Types:"));
String[] dataTypeList = new String[dataLength];
//Fill up dataTypeList with user input
writeJavaFile(dataTypeList);
}
public void writeJavaFile(String[] dataTypes){
//Create the new class and its methods here using the array of dataTypes
}
}
Which, for example, will then create a class of methods similar to this:
public class ActualClass(){
public String validate'What The dataTypes[x] was'(String infoToValidate){
if(etc etc){
return "etc etc";
}else{
return "";
}
}
}
You can create, compile and instantiate a java class in runtime.
See this:
http://www.java-tips.org/java-se-tips/java.lang/create-a-java-source-dynamically-compile-and.html
Some libraries:
cglib
Codemodel
Or you could use Nashorn. (javascript interpreter) I can imagine a use case where user defines complex validation in javascript and then this would be a good approach.
Although in your case I would not recommend any of the above and just write it in the code. Data types validation sounds like something you want to have hard-coded.
I can tell you right off that bat you are approaching a simple problem with an incredibly complex solution...
I would guess you are looking for the instanceof keyword, or perhaps an abstract validation class.
If you could be more specific with your intended functionality we could help you come up with a reasonable design pattern.
Directly to your question:
Yes, you can generate and load classes in Java on the fly. It involves invoking the defineClass(String, byte[], int, int) method in the reflection package. As input to this function you have to provide a byte array of the class you are instantiating. This doesn't sound like the appropriate approach to this problem.

Is Javascript constructor function equivalent/similar to a class or interface in Java

I am trying to pick up the basics of Java and I am more familiar with JavaScript.
Is the following statement accurate (I just need high level understanding):
Javascript constructor function or factory function is the equivalent (i am using this word loosely here) of a class or interface in Java.
EDIT:
This is what I am reading in a Java book:
A Java program is mostly a collection objects talking to other
objects by invoking each other's methods. Every object is of a
certain type, and that type is defined by a class or an
interface. Most Java programs use a collection of many different types.
Coming from Javascript, above sounds very much like JS constructor function is similar to a class in Java where the objects properties and methods would be defined.
I know Java and JavaScript are two separate languages.
Thanks
I'd say you're close. Constructor functions (and prototypes) in JavaScript are the closest thing to Java classes that we have in JS; but they're certainly not "equivalent".
You can dynamically add or remove properties and methods to the prototype of a JavaScript constructor; you can't add or remove things from a Java class at runtime.
Example:
function Foo() {}
Foo.prototype.hello = function() { alert('hello'); };
var f = new Foo();
f.hello(); // alerts 'hello'
delete Foo.prototype.hello;
f.hello(); // throws an error
You can achieve "inheritance" at runtime in JavaScript simply by assigning the prototypes of constructor functions to arbitrary objects. In Java you declare inheritance at compile-time and it cannot be changed at runtime.
Example:
function EnglishSpeaker() {}
EnglishSpeaker.prototype.greet = function() { return 'hello'; };
function SpanishSpeaker() {}
SpanishSpeaker.prototype.greet = function() { return 'hola'; };
function Me() {}
Me.prototype = EnglishSpeaker.prototype;
var me = new Me();
me instanceof EnglishSpeaker; // true
me.greet(); // 'hello'
Me.prototype = SpanishSpeaker.prototype;
me = new Me();
me instanceof EnglishSpeaker; // false
me instanceof SpanishSpeaker; // true
me.greet(); // 'hola'
In JavaScript a prototype is simply an object. So a "class" (constructor function) can "inherit" from any plain object; thus there is a much looser distinction between "types" and "values".
Example:
function Thing() {}
var randomObject = { foo: 1, bar: 2 };
Thing.prototype = randomObject;
var thing = new Thing();
thing.foo; // 1
In Java you can define an interface which some class must implement. JavaScript doesn't really provide any such mechanism.
These are just some of the differences off the top of my head. Point is: they're similar, and you're right to draw a connection. But they are definitely not the same.
JavaScript:
function Cat(name) {
this.name = name;
this.talk = function() {
alert( this.name + " says meeow!" );
};
}
var cat1 = new Cat("Felix");
in Java:
public class Cat {
private String name;
public Cat(String name) {
this.name = name;
this.talk();
}
public void talk() {
System.out.println( this.name + " says meeow!" );
}
}
Cat cat1 = new Cat("Felix");
From source :Does JavaScript have the interface type (such as Java's 'interface')?
JavaScript inheritance is based on objects, not classes. That's not a big deal until you realize:
JavaScript is an extremely dynamically typed language -- you can create an object with the proper methods, which would make it conform to the interface, and then undefine all the stuff that made it conform. It'd be so easy to subvert the type system -- even accidentally! that it wouldn't be worth it to try and make a type system in the first place.
If you're coming from JavaScript and learning Java, there's one huge difference that I don't think anyone else has mentioned yet.
In JavaScript, a function is an object. An object can contain properties whose values can be function objects, or they can be other objects or primitive values. When you call obj.method(arguments), the semantics are to look for a method property of the object (or a prototype), and if it's a function object, to call it.
In Java and other compiled languages with OOP features, functions are not objects. If you create a new object of a particular type, the "type" information in the object refers to a list of polymorphic functions for that type. That's how polymorphism works in these languages. If you call obj.method(arguments), and method is a method that can be overridden for derived types, then the program looks up obj's type, and then looks in the function list for the type to determine which function to call. What this means, to me, is that the object's type is a key piece of information in these languages, and OOP revolves around it; while in JavaScript, the "type" of an object is quite a bit less important, since the function itself is looked up by name in the object. One can use JavaScript in a way to make it look like it's emulating the way other languages handle OOP, but it's not required, and it's not a built-in part of the language.
I think you have to keep that in mind when going from one to the other. If you try too hard to relate Java features to JavaScript features you're already familiar with, it will be confusing.
If you are new to Java, I suggest you go to amazon.com and look for a beginning book on java that has good reviews and read it cover to cover. I think this will be the best use of your time rather than reading varoius articles on Java and picking it up piece-meal. I also suggest you don't try to port your knowledge of Javascript to Java, least you make learning Java that much harder. Note there are many books you can read for Java (web) development: Java, products built on Java (JSF, Tomcat, etc), and supporting technologies (HTML, CSS, XML, etc).

How to simplify a class without writing methods that are already simple?

I have a complex class and I want to simplify it by implementing a facade class (assume I have no control on complex class). My problem is that complex class has many methods and I will just simplify some of them and rest of the will stay as they are. What I mean by "simplify" is explained below.
I want to find a way that if a method is implemented with facade then call it, if not then call the method in complex class. The reason I want this is to write less code :) [less is more]
Example:
Facade facade = // initialize
facade.simplified(); // defined in Facade class so call it
// not defined in Facade but exists in the complex class
// so call the one in the complex class
facade.alreadySimple();
The options that comes to mind mind are:
Option 1: Write a class holding a variable of complex class and implement complex ones then implement simple ones with direct delegation:
class Facade {
private PowerfulButComplexClass realWorker = // initialize
public void simplified() {
// do stuff
}
public void alreadySimple() {
realWorker.alreadySimple();
}
// more stuff
}
But with this approach I will need to implement all the simple methods with just a single delegation statement. So I need to write more code (it is simple though)
Option 2: Extend the complex class and implement simplified methods but then both simple and complex versions of these methods will be visible.
In python I can achieve similar behaviour like this:
class PowerfulButComplexClass(object):
def alreadySimple(self):
# really simple
# some very complex methods
class Facade(object):
def __init__(self):
self.realworker = PowerfulButComplexClass()
def simplified(self):
# simplified version of complex methods in PowerfulButComplexClass
def __getattribute__(self, key):
"""For rest of the PowerfulButComplexClass' methods use them as they are
because they are simple enough.
"""
try:
# return simplified version if we did
attr = object.__getattribute__(self, key)
except AttributeError:
# return PowerfulButComplexClass' version because it is already simple
attr = object.__getattribute__(self.data, key)
return attr
obj = Facace()
obj.simplified() # call the one we have defined
obj.alreadySimple( # call the one defined in PowerfulButComplexClass
So what is the Java way to achieve this?
Edit: What I mean by "simplify": A complex method can be either a method with too many arguments
void complex method(arg1, arg2, ..., argn) // n is sufficiently large
or a set of related methods that will almost always called together to achieve a single task
outArg1 = someMethod(arg1, arg2);
outArg2 = someOtherMethod(outArg1, arg3);
actualResult = someAnotherMethod(outArg2);
so we want to have something like this:
String simplified(arg1, arg2, arg3) {
outArg1 = someMethod(arg1, arg2);
outArg2 = someOtherMethod(outArg1, arg3);
return someAnotherMethod(outArg2);
}
It's called Inheritence. Consider the following code:
class Complex {
public function complex() { /* Complex Function */ }
public function simple() { /* Already simple function */ }
}
class SimplifiedComplex extends Complex {
public function complex() { /* Simplify Here */ }
}
The simple() method will work on a SimplifiedComplex object.
I think you've already called it. I would go with Option 1. It provides the most flexibility given the rigidity of java.
I prefer it because it favors composition over inheritance. Although this creates more code, I find designs like this generally are easier to modify in the long run.
Inheritance should only be used to model strict "is a" relationships where the subclass necessarily has all the properties and behaviors of the base class. If you're using inheritance for anything else your asking for trouble.
Finally, I don't buy into the idea of "Less Is More"(Insert incredibly concise, indecipherable perl example here). I buy into the principle of "Code should be as simple as it needs to be and no simpler".
Depending on your use case, you might want to create a facade in front of some of the functionality in complex class by delegating (Option 1), and instead of providing support for the rest of the functionality in complex class, you provide means to access complex class directly (getComplexClass).
This might make the design clearer. Consider, for example, a complex class handling most of the features of a bank system. Creating a class named "Account" that has access to the complex class but only uses the methods relevant for a bank account helps the design. For convenience, the Account class could have a method getBankSystemForAccount or something similar.
This is ugly in Java, but you can write a function that takes the name of the method you want to call, and a parameter list, and use reflection to find the appropriate method to call. This will be conceptually similar to how you'd do it in Python, except much uglier.

Java create dynamic class

I have 2 questions that I was hoping someone could help me with. Is there a way to create a class on the fly with android/java and also add variables to the class? For example I would like to do something like this:
Class c = new Class();
c.name = 'testing';
c.count = 0;
c.getName = new function(){
return c.name;
}
Just wondering if this is possible or if there is another way to do this. Basically I want to build an object that I can use the data from as an object.
No, the syntax you describe is not possible in Java. I'm not sure what you are trying to accomplish there. If you want to create a class to use to hold data on the fly, you can create an anoynmous inner class.
Object object = new Object() {
private String name = testing;
private int count = 0;
public String getName() {
return name;
}
}
In general, I wouldn't use this for a data objects though. This functionality is typically used for anonymous implementations of interfaces to support callbacks, etc.
This is not typically done. It can be done by reflection, but would be a fairly bad idea--This type of code is really annoying to debug, won't interact correctly in the IDE (For instance, ctrl-clicking on an instance of c.getName wouldn't be able to jump to where the method is defined), it would probably be a pretty big performance hit, etc.
However, for some generic tools this is possible. I believe Hibernate might have the ability to create classes from DB tables.
The most common use, however, is in mocking used within testing frameworks--They can do almost exactly what you want. Look at EasyMock with TestNG.
In general, though, you are better off just defining a business class and going with it rather than trying to make some abstract framework that generates your classes for you.

Categories

Resources