Can you dynamically rename a class name? - java

Is it possible in Java to give a class or even its functions a new name at run time. By reading in the new names as arguments or on a configuration file when the program is started?
UPDATE:
Here is the purpose of this. I am using Java Script Engine to allow any JSR 223 compatible Scripting Language to access our API. Some of our clients are not used to using Java and it's naming conventions and would feel more comfortable using their own specific naming conventions. So I am required to give them the capability to dynamically change the API's class and function names without actually changing them in the code. It was suggested I use a Map and some sort of binding with a string name and the actual Java name e.g.,
map.put("Hello",HelloWorld.class)
Object obj = new Hello();
which should be the same as,
Object obj = new HelloWorld();
If this is not possible please tell me why. I need a solid Java expertise answer. This is out of my league and I need facts to tell people why this is not possible even though myself I am almost sure it's not possible.
Possible Solution:
Here is the closets solution I have come up with. Using this link,
https://weblogs.java.net/blog/2005/08/10/reflection-and-dynamically-changing-classes
I could add in the names at run time, use composition to create an Adapter Class, and then compile the file, and voila the Script Language folks could use their defined names instead of my API's Java names.
Is this the only conceivable way to accomplish this?
UPDATE 2:
Here is another possible solution for anyone trying this too,
http://asm.ow2.org/doc/faq.html
That'll take you directly to their frequently asked questions which will have one for this exact problem.

No, you will need to refactor for references and recompile for execution.

Yes, you are able to do that using javassist.
In particular, you have to edit NewExpr.

Related

Can parameterized generic class instance have different methods depending on type argument?

While answering following question:
How do I create a Builder that can build more than one kind of Java object? I thought that it's impossible to achieve the following in Java:
public class Builder<T> {
// ...
}
Builder<User> userBuilder = new Builder<User>();
// here userBuilder only has method 'name'
userBuilder.name("John");
Builder<Country> countryBuilder = new Builder<Country>();
// here countryBuilder only has method 'code'
countryBuilder.code("UA");
But, in the comments, user John Feminella told that it is actually possible using custom class loaders.
Now, I know basics of class loaders in Java, but really have no idea how they can alter Java syntax. Could someone give basic idea on how this can be achieved?
Thanks in advance!
P.S. No need for long code snippets - short explanation using standard terms would do.
The reason it's hard is because Java's built-in classloader will not reload a class once it's been added, and reloading a class is required (in Java) to add methods dynamically. Furthermore, the ClassLoader.resolve() method is final, meaning a custom class loader can't override it. This has a number of effects, but the most important one is that if you want to reload a class, you must instantiate a new ClassLoader every time you want to load it.
That's enormously expensive, so there's really no practical reason to try and work around the limitations of Java this way. (You should be using another language more suited to this sort of work, like JRuby.) Dynamically loading things is possible, but it's just not worth it.
But, assuming you're willing to suffer some pain, can you do it? Absolutely. See, e.g., this article. The strategy used there is to:
compile Java code at runtime
load/reload Java class at runtime via a proxy class
link the up-to-date class to its caller

enterprise architect scripting: missed method in java api eaapi.jar

In the Reference of the Enterprise Architect Object Model I found the class Element:
http://www.sparxsystems.com/enterprise_architect_user_guide/9.3/automation/element2.html
The class Element contains the attribute IsComposite. I use the Java API (eaapi.jar) of Sparx Systems and can't find the Setter for this attribute (myElement.SetIsComposite(true) isn't possible).
Does anybody know a solution for this problem? For example an updated lib of eaapi.jar or a workaround?
Regards,
Phil
EA's Java API is a wrapper for the underlying COM API, which is what's documented in the help file. The Java version is generally a step or two behind the COM version.
It would appear that this method has been left out of the Java API. Other properties in the COM classes have getters/setters in the Java API, but this one doesn't. The same is true in version 10.0.1009.
In EA 11.0.1105 (the first general release of EA 11), Element.SetCompositeDiagram() was added, but this too seems to be limited to the COM API: reverse-engineering eaapi.jar reveals no corresponding method.
From here there would appear to be three alternatives open to you:
Report the issue to Sparx Systems and ask them to add the relevant methods to the Java API.
Rewrite your code in C# to make use of the full API.
Use the undocumented Repository.Execute() method to manipulate the underlying database directly.
An element's "compositeness" is represented by the value 8 in the t_object.NType column, but this column is overloaded, that is to say the interpretation of its value depends on other columns as well, and furthermore is undocumented. So this is not a good solution if you want maintainability.
If you want to go this way, first add the diagram and then do something like this:
repository.Execute("update t_object set NType = 8 where Object_ID = " +
element.ElementID);
I think that would work, but I haven't tested it. If there are more than one diagrams in the element, I think the first one gets picked. But all this is essentially guesswork, so if you want to build something that you know will work, switch to C#.

Will Java have a way for non-library developers to use extension methods?

C#'s extension methods are great for adding syntactic sugar. Java extension methods are great for allowing library developers to add methods to their interfaces.
I am a non-library Java developer and know I will reap a lot of benefits from getting new functionality from libraries, but I would still like to have the syntactic sugar capabilities of C# extension methods.
Is this, or will this be possible in future versions of Java?
eg: I would like to add methods to the String class...
String data = StringUtils.capitalize("abcd"); // instead of this
String data = "abcd".capitalize() // I would like to do this
Please don't focus on this particular example, I am only showing the class of functionality I want to be able to achieve.
Java does not have this feature, nor is it likely to have it anytime soon.
Groovy however does have a very similar feature, and it also runs on the JVM. Perhaps that's an option.
I suspect you're thinking of a planned addition to Java 8 that will allow you to add methods, with default implementations, to an interface -- so that you can add new methods without breaking all existing code. This is only of use to you if you control the interface type -- so it would not be of use for String, because String is not an interface.

from java to javascript: the object model

I'm trying to port an application I wrote in java to javascript (actually using coffeescript).
Now, I'm feeling lost.. what do you suggest to do to create class properties? Should I use getter/setters? I don't like to do this:
myObj.prop = "hello"
because I could use non existing properties, and it would be easy to mispell something..
How can I get javascript to be a bit more like java, with private, public final properties etc..? Any suggestion?
If you just translate your Java code into JavaScript, you're going to be constantly fighting JavaScript's object model, which is prototype-based, not class-based. There are no private properties on objects, no final properties unless you're using an ES5-compatible engine (you haven't mentioned what your target runtime environment is; browsers aren't use ES5-compatible, it'll be another couple of years), no classes at all in fact.
Instead, I recommend you thoroughly brief yourself on how object orientation actually works in JavaScript, and then build your application fully embracing how JavaScript does it. This is non-trivial, but rewarding.
Some articles that may be of use. I start with closures because really understanding closures is absolutely essential to writing JavaScript, and most "private member" solutions rely on closures. Then I refer to a couple of articles by Douglas Crockford. Crockford is required reading if you're going to work in JavaScript, even if you end up disagreeing with some of his conclusions. Then I point to a couple of articles specifically addressing doing class-like things.
Closures are not complicated - Me
Prototypical inheritance in JavaScript - Crockford
Private Members in JavaScript - Crockford
Simple, Efficient Supercalls in JavaScript - Me Includes syntactic sugar to make it easier to set up hierarchies of objects (it uses class-based terminology, but actually it's just prototypical inheritance), including calling "superclass" methods.
Private Members in JavaScript - Me Listing Crockford's solution and others
Mythical Methods - Me
You must remember this - Me
Addressing some of your specific questions:
what do you suggest to do to create class properties? Should I use getter/setters? I don't like to do this:
myObj.prop = "hello"
because I could use non existing properties, and it would be easy to mispell something..
I don't, I prefer using TDD to ensure that if I do have a typo, it gets revealed in testing. (A good code-completing editor will also be helpful here, though really good JavaScript code-completing editors are thin on the ground.) But you're right that getters and setters in the Java sense (methods like getFoo and setFoo) would make it more obvious when you're creating/accessing a property that you haven't defined in advance (e.g., through a typo) by causing a runtime error, calling a function that doesn't exist. (I say "in the Java sense" because JavaScript as of ES5 has a different kind of "getters" and "setters" that are transparent and wouldn't help with that.) So that's an argument for using them. If you do, you might look at using Google's Closure compiler for release builds, as it will inline them.
How can I get javascript to be a bit more like java, with private...
I've linked Crockford's article on private members, and my own which lists other ways. The very basic explanation of the Crockford model is: You use a variable in the context created by the call to your constructor function and a function created within that context (a closure) that has access to it, rather than an object property:
function Foo() {
var bar;
function Foo_setBar(b) {
bar = b;
}
function Foo_getBar() {
return bar;
}
this.setBar = Foo_setBar;
this.getBar = Foo_getBar;
}
bar is not an object property, but the functions defined in the context with it have an enduring reference to it. This is totally fine if you're going to have a smallish number of Foo objects. If you're going to have thousands of Foo objects you might want to reconsider, because each and every Foo object has its own two functions (really genuinely different Function instances) for Foo_getBar and Foo_setBar.
You'll frequently see the above written like this:
function Foo() {
var bar;
this.setBar = function(b) {
bar = b;
};
this.getBar = function() {
return bar;
};
}
Yes, it's briefer, but now the functions don't have names, and giving your functions names helps your tools help you.
How can I get javascript to be a bit more like java, with...public final properties
You can define a Java-style getter with no setter. Or if your target environment will be ES5-compliant (again, browsers aren't yet, it'll be another couple of years), you could use the new Object.defineProperty feature that allows you to set properties that cannot be written to.
But my main point is to embrace the language and environment in which you're working. Learn it well, and you'll find that different patterns apply than in Java. Both are great languages (I use them both a lot), but they work differently and lead to different solutions.
You can use module pattern to make private properties and public accessors as one more option.
This doesn't directly answer your question, but I would abandon the idea of trying to make the JavaScript app like Java. They really are different languages (despite some similarities in syntax and in their name). As a general statement, it makes sense to adopt the idioms of the target language when porting something.
Currently there are many choices for you , you can check dojo library. In dojo, you can code mostly like java programming
Class
Javascript doesn’t have a Class system like Java,dojo provide dojo.declare to define a functionality to simulate this. Check this page . There are field variable, constructor method, extend from other class.
JavaScript has a feature that constructor functions may return any object (not necesserily this). So, your constructor function could just return a proxy object, that allows access only to the public methods of your class. Using this method you can create real protected member, just like in Java (with inheritance, super() call, etc.)
I created a little library to streamline this method: http://idya.github.com/oolib/
Dojo is one option. I personally prefer Prototype. It also has a framework and API for creating classes and using inheritance in a more "java-ish" way. See the Class.create method in the API. I've used it on multiple webapps I've worked on.
I mainly agree with #Willie Wheeler that you shouldn't try too hard to make your app like Java - there are ways of using JavaScript to create things like private members etc - Douglas Crockford and others have written about this kind of thing.
I'm the author of the CoffeeScript book from PragProg. Right now, I use CoffeeScript as my primary language; I got fluent in JavaScript in the course of learning CoffeeScript. But before that, my best language was Java.
So I know what you're going through. Java has a very strong set of best practices that give you a clear idea of what good code is: clean encapsulation, fine-grained exceptions, thorough JavaDocs, and GOF design patterns all over the place. When you switch to JavaScript, that goes right out the window. There are few "best practices," and more of a vague sense of "this is elegant." Then when you start seeing bugs, it's incredibly frustrating—there are no compile-time errors, and far fewer, less precise runtime errors. It's like playing without a net. And while CoffeeScript adds some syntactic sugar that might look familiar to Java coders (notably classes), it's really no less of a leap.
Here's my advice: Learn to write good CoffeeScript/JavaScript code. Trying to make it look like Java is the path to madness (and believe me, many have tried; see: just about any JS code released by Google). Good JS code is more minimalistic. Don't use get/set methods; use exceptions sparingly; and don't use classes or design patterns for everything. JS is ultimately a more expressive language than Java is, and CoffeeScript even moreso. Once you get used to the feeling of danger that comes with it, you'll like it.
One note: JavaScripters are, by and large, terrible when it comes to testing. There are plenty of good JS testing frameworks out there, but robust testing is much rarer than in the Java world. So in that regard, there's something JavaScripters can learn from Java coders. Using TDD would also be a great way of easing your concerns about how easy it is to make errors that, otherwise, wouldn't get caught until some particular part of your application runs.

Dynamic Java Variable Naming

This question is more for furthering my knowledge than anything...
Does Java have anything similar to PHP's ability to generate a variable name? I have an SCJA Cert and I'm studying for the SCJP and have never seen this, but was curious.
PHP Example
$application->{$request->getParameter("methodCall")}($request->getParameter('value'));
Does Java have anything similar? I've been reading on here and the general answer is to use a HashMap which I'm not interested in since this isn't to solve a real problem. I'm more interested in the is this possible solution? If not so be it, but just trying to expand my knowledge!
Thanks,
Jared
No, variables (fields and local variables) are statically "created" at compile-time in Java.
Of course memory is only ever occupied at runtime, but how many and which fields an object has is decided at compile-time.
Therefore you can't "dynamically add a field" in Java.
And yes: A Map is the solution to the problem. "Adding a field" is not usually the problem but an attempted solution that's appropriate for some languages (usually dynamic ones) and inappropriate for others.
I think you mean a field in a class. A local variable can only be used in a method.
To generate a field in a class or a variable, you need to generate Java code and compile it or byte code at runtime. It can be done but is 100x more complicated than using a simple Map. (I have done it dynamically before and I wouldn't recommend it unless you really have to)
If you want to do code generation I would suggest using Objectweb's ASM.
This can't be done...Java Reflection only allows you to view the structure of a class but not append to it.

Categories