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.
Related
just wondering if anyone can help me out with something.
Basically I have two objects from different places for example two different car classes. I want to map the properties of class carA to the properties of class carB using a mapper I have created. This is simple enough in most scenarios as can be seen below.
public carB carMapper(carA car){
carB carb = new carB();
carb.weight = car.weight
carb.size = car.size
}
However, there are some scenarios where class CarA stores the corresponding values in a slightly different format to that of CarB, ie, for a model of car which is a Ford carA stores this as Frd but carB stores it as Ford. Is there an easy way (perhaps using enums or something) that I can map these correctly? I know I could do
if (carA.model = frd)
then carB.model = Ford
etc but I dont want to do this for every scenario.... I know the possible values of both carA and carB, could I use an enum in some way to help me out here?
Thanks.
It appears that you are looking for something like a mapping constructor. There is already a well-known concept called a copy constructor which helps you create a copy of an object of a given class. In your case, you want to create an instance of some class given an instance of another class.
I do not think enums can be (or should be) used for this purpose, mainly because they are not designed for this purpose.
It's not very clear if such a construct is immensely useful (and generic). For instance, would you want to create a Turtle given a Car? There isn't much common between them, so providing such a facility seems to be of little value. You are taking an example of CarA and CarB as classes, but since they are two different classes, they are to be assumed entirely different things, any commonality should be assumed purely coincidental.
If you do want to externalize this operation, then you may consider using some kind of serialization for your mapping in a format like JSON or XML and then one can imagine generic processing of that format to create objects of classes involved:
<map from="CarA" to="CarB">
<property>model</property>
<override>Ford</override>
</map>
In this case, you create an instance of CarB and reflectively set the fields on it based on the mappings. You can make an assumption that all the other fields are copied verbatim. Of course, you will need to flush out all the details of your specification for it to be generically useful.
Otherwise, I don't see anything wrong with the if-else construct you have alluded to, since its usefulness is decidedly limited.
Thanks for the feedback guys, appreciate the responses, sorry I haven't had a chance to reply sooner. I have found a solution to my problem using an enum. It suits exactly what I was looking for, maybe for some reason it isnt ideal but if anyone can think of some reason I shouldn't be using an enum in this way I am more than happy to hear it. Anyway, my solution is below and allows me to add multiple values etc:
public enum ModelMapper
{
Ford("Ford", "frd"),
Renault("Renault", "rnlt");
private final String carAValue;
private final String carBValue;
ModelMapper(String carA_value, String carB_value)
{
carAValue = carA_value;
carBValue = carB_value;
}
public static String getCarAValue(String carB_value)
{
for (ModelMapper m: ModelMapper.values()) {
if (m.carBValue.equals(carB_value)) {
return m.carAValue;
}
}
throw new IllegalArgumentException(carB_value);
}
}
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;
}
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!
I'm attempting to write a framework to handle an interface with an external library and its API. As part of that, I need to populate a header field that exists with the same name and type in each of many (70ish) possible message classes. Unfortunately, instead of having each message class derive from a common base class that would contain the header field, each one is entirely separate.
As as toy example:
public class A
{
public Header header;
public Integer aData;
}
public class B
{
public Header header;
public Long bData;
}
If they had designed them sanely where A and B derived from some base class containing the header, I could just do:
public boolean sendMessage(BaseType b)
{
b.header = populateHeader();
stuffNecessaryToSendMessage();
}
But as it stands, Object is the only common class. The various options I've thought of would be:
A separate method for each type. This would work, and be fast, but the code duplication would be depressingly wasteful.
I could subclass each of the types and have them implement a common Interface. While this would work, creating 70+ subclasses and then modifying the code to use them instead of the original messaging classes is a bridge too far.
Reflection. Workable, but I'd expect it to be too slow (performance is a concern here)
Given these, the separate method for each seems like my best bet, but I'd love to have a better option.
I'd suggest you the following. Create a set of interfaces you'd like to have. For example
public interface HeaderHolder {
public void setHeader(Header header);
public Header getHeader();
}
I'd like your classes to implement them, i.e you's like that your class B is defined as
class B implements HeaderHolder {...}
Unfortunately it is not. Now problem!
Create facade:
public class InterfaceWrapper {
public <T> T wrap(Object obj, Class<T> api) {...}
}
You can implement it at this phase using dynamic proxy. Yes, dynamic proxy uses reflection, but forget about this right now.
Once you are done you can use your InterfaceWrapper as following:
B b = new B();
new IntefaceWrapper().wrap(b, HeaderHolder.class).setHeader("my header");
As you can see now you can set headers to any class you want (if it has appropriate property). Once you are done you can check your performance. If and only if usage of reflection in dynamic proxy is a bottleneck change the implementation to code generation (e.g. based on custom annotation, package name etc). There are a lot of tools that can help you to do this or alternatively you can implement such logic yourself. The point is that you can always change implementation of IntefaceWrapper without changing other code.
But avoid premature optimization. Reflection works very efficiently these days. Sun/Oracle worked hard to achieve this. They for example create classes on the fly and cache them to make reflection faster. So probably taking in consideration the full flow the reflective call does not take too much time.
How about dynamically generating those 70+ subclasses in the build time of your project ? That way you won't need to maintain 70+ source files while keeping the benefits of the approach from your second bullet.
The only library I know of that can do this Dozer. It does use reflection, but the good news is that it'll be easier to test if it's slow than to write your own reflection code to discover that it's slow.
By default, dozer will call the same getter/setters on two objects even if they are completely different. You can configure it in much more complex ways though. For example, you can also tell it to access the fields directly. You can give it a custom converter to convert a Map to a List, things like that.
You can just take one populated instance, or perhaps even your own BaseType and say, dozer.map(baseType, SubType.class);
I have a pipeline-based application that analyzes text in different languages (say, English and Chinese). My goal is to have a system that can work in both languages, in a transparent way. NOTE: This question is long because it has many simple code snippets.
The pipeline is composed of three components (let's call them A, B, and C), and I've created them in the following way so that the components are not tightly coupled:
public class Pipeline {
private A componentA;
private B componentB;
private C componentC;
// I really just need the language attribute of Locale,
// but I use it because it's useful to load language specific ResourceBundles.
public Pipeline(Locale locale) {
componentA = new A();
componentB = new B();
componentC = new C();
}
public Output runPipeline(Input) {
Language lang = LanguageIdentifier.identify(Input);
//
ResultOfA resultA = componentA.doSomething(Input);
ResultOfB resultB = componentB.doSomethingElse(resultA); // uses result of A
return componentC.doFinal(resultA, resultB); // uses result of A and B
}
}
Now, every component of the pipeline has something inside which is language specific. For example, in order to analyze Chinese text, I need one lib, and for analyzing English text, I need another different lib.
Moreover, some tasks can be done in one language and cannot be done in the other. One solution to this problem is to make every pipeline component abstract (to implement some common methods), and then have a concrete language-specific implementation. Exemplifying with component A, I'd have the following:
public abstract class A {
private CommonClass x; // common to all languages
private AnotherCommonClass y; // common to all languages
abstract SomeTemporaryResult getTemp(input); // language specific
abstract AnotherTemporaryResult getAnotherTemp(input); // language specific
public ResultOfA doSomething(input) {
// template method
SomeTemporaryResult t = getTemp(input); // language specific
AnotherTemporaryResult tt = getAnotherTemp(input); // language specific
return ResultOfA(t, tt, x.get(), y.get());
}
}
public class EnglishA extends A {
private EnglishSpecificClass something;
// implementation of the abstract methods ...
}
In addition, since each pipeline component is very heavy and I need to reuse them, I thought of creating a factory that caches up the component for further use, using a map that uses the language as the key, like so (the other components would work in the same manner):
public Enum AFactory {
SINGLETON;
private Map<String, A> cache; // this map will only have one or two keys, is there anything more efficient that I can use, instead of HashMap?
public A getA(Locale locale) {
// lookup by locale.language, and insert if it doesn't exist, et cetera
return cache.get(locale.getLanguage());
}
}
So, my question is: What do you think of this design? How can it be improved? I need the "transparency" because the language can be changed dynamically, based on the text that it's being analyzed. As you can see from the runPipeline method, I first identify the language of the Input, and then, based on this, I need to change the pipeline components to the identified language. So, instead of invoking the components directly, maybe I should get them from the factory, like so:
public Output runPipeline(Input) {
Language lang = LanguageIdentifier.identify(Input);
ResultOfA resultA = AFactory.getA(lang).doSomething(Input);
ResultOfB resultB = BFactory.getB(lang).doSomethingElse(resultA);
return CFactory.getC(lang).doFinal(resultA, resultB);
}
Thank you for reading this far. I very much appreciate every suggestion that you can make on this question.
The factory idea is good, as is the idea, if feasible, to encapsulate the A, B, & C components into single classes for each language. One thing that I would urge you to consider is to use Interface inheritance instead of Class inheritance. You could then incorporate an engine that would do the runPipeline process for you. This is similar to the Builder/Director pattern. The steps in this process would be as follows:
get input
use factory method to get correct interface (english/chinese)
pass interface into your engine
runPipeline and get result
On the extends vs implements topic, Allen Holub goes a bit over the top to explain the preference for Interfaces.
Follow up to you comments:
My interpretation of the application of the Builder pattern here would be that you have a Factory that would return a PipelineBuilder. The PipelineBuilder in my design is one that encompases A, B, & C, but you could have separate builders for each if you like. This builder then is given to your PipelineEngine which uses the Builder to generate your results.
As this makes use of a Factory to provide the Builders, your idea above for a Factory remains in tact, replete with its caching mechanism.
With regard to your choice of abstract extension, you do have the choice of giving your PipelineEngine ownership of the heavy objects. However, if you do go the abstract way, note that the shared fields that you have declared are private and therefore would not be available to your subclasses.
I like the basic design. If the classes are simple enough, I might consider consolidating the A/B/C factories into a single class, as it seems there could be some sharing in behavior at that level. I'm assuming that these are really more complex than they appear, though, and that's why that is undesirable.
The basic approach of using Factories to reduce coupling between components is sound, imo.
If I'm not mistaken, What you are calling a factory is actually a very nice form of dependency injection. You are selecting an object instance that is best able to meet the needs of your parameters and return it.
If I'm right about that, you might want to look into DI platforms. They do what you did (which is pretty simple, right?) then they add a few more abilities that you may not need now but you may find would help you later.
I'm just suggesting you look at what problems are solved now. DI is so easy to do yourself that you hardly need any other tools, but they might have found situations you haven't considered yet. Google finds many great looking links right off the bat.
From what I've seen of DI, it's likely that you'll want to move the entire creation of your "Pipe" into the factory, having it do the linking for you and just handing you what you need to solve a specific problem, but now I'm really reaching--my knowledge of DI is just a little better than my knowledge of your code (in other words, I'm pulling most of this out of my butt).