find out instantiating object in the constructor of a class - java

How can i get hold of the instantiating object from a constructor in java?
I want to store reference to the parent object for some GUI classes to simulate event bubbling - calling parents handlers - but i dont wanna change all the existing code.

Short answer: there isn't a way to do this in Java. (You can find out what class called you, but the long answer below applies there for the most part as well.)
Long answer: Code that magically behaves differently depending on where it's being invoked from is almost always a bad idea. It's confusing to whoever has to maintain your code, and it seriously hurts your ability to refactor. For example, suppose you realize that two of the places instantiating your object have basicaly the same logic, so you decide to factor out the common bits. Surprise! Now the code behaves differently because it's being instantiated from somewhere else. Just add the parameter and fix the callers. It'll save you time in the long run.

If you want to know the invoking class, then pass "this" as a parameter to the constructor.
Thing thing = new Thing(this);
Edit: A modern IDE allowing refactoring will make this very easy to do.

Intercepting method calls (including constructors) without changing a ton of existing code is one thing Aspect-oriented programming was made for.
Check out AspectJ for a start.
With AspectJ, you can define a "pointcut" that specifies that you want to intercept constructor calls for a certain object or set of objects (using wildcards if need be), and within the interception code ("advice"), you will be given method context, which includes information about the both the calling method and object.
You can even use AspectJ to add fields to your object's to store the parent reference without modifying their existing code (this is called "introduction").

Related

How do you create an aspect with per class, per object and per method/source-location parts in AOP using AspectJ

I want to create an aspect instance per class, per object and per method/source-location parts.
More particularly:
Some values only change from class to class, but needs to be computed only once per class, hence they need to be deduced once per class. E.g. storing the Class would be per class, also a reference to the Logger for a particular class for logging.
Some values change from method to method, but needs to be computed only once per method, hence they need to be deduced once per method. E.g. the method signature would be per method per class. This data does not change due to object instance or invocation.
Some values change from instance/object to instance/object, but needs to be computed only once per instance/object, hence they need to be deduced once per instance/object. E.g. object ID, which would be instance dependent.
Some values change from object to object, but needs to be computed only once per object per field or method, hence they need to be deduced once per object per field or method. E.g. invocation count of a method, which would be method and object dependent.
Some values change from call to call, hence they need to be deduced/computed for every call. E.g. getting method parameters in AspectJ. This is dependent on the method, object and call.
I am trying to create aspects which store these deduced/computed values. In order not to incur more than whats is needed in terms of memory and computing. How can this be implemented in Eclipse AspectJ AOP?
What I have being trying to do so far was to create a hierarchy like this:
aspect Base {
// Singleton - data items for the whole program computed and stored once
// This is shared across all the objects in the application regardless of the class
protected pointcut executionJoinPoints(): !within(Base+) && execution (* *.*(..));
}
aspect PerClass extends Base perthis(executionJoinPoints()) {
// Per class - store class-specific data computed and stored once per class
// Since this is class-specific, need to know what class this corresponds to
// This is shared across all the objects of the same class
}
aspect PerMethodPerClass extends PerClass percflow(executionJoinPoints()) {
// Per method - store method specific data computed and stored once per method as fields
// Since this is method-specific, need to know what method this corresponds to
// This is shared across all the objects of the same class
}
aspect PerObject extends PerMethodPerClass perthis(executionJoinPoints()) {
// Per object/instance - store object/instance-specific data computed and stored once per object
// Since this is object/instance-specific, need to know what object/instance this corresponds to
// This is specific to the object/instance
}
aspect PerMethodPerObject extends PerObject percflow(executionJoinPoints()) {
// Per method per object - store method specific data computed and stored once per method as fields for every object instance
// Since this is method-specific, need to know what method this corresponds to and also what object this corresponds to
// This is specific to the object/instance and particular method
}
public aspect PerCall extends PerMethodPerInstance {
// Per call - handle data which change from call to call
// This is specific to the call or invocation or execution
}
I am trying to implement:
logging and tracing
metrics and statistics collection for the program execution
using AspecJ AOP. For the statistics, I collect I need an aspect instance per class, per object and per method/source-location parts to store and collect the relevant data.
E.g. a method related statistics will be computed and stored in a PerMethod aspect. Also, it will be easier to lookup method-specific counters are accessible instance than looking it up in a large data structure. What is required here is that the aspect is instantiated once for each method. Similarly for classes, objects, etc.
Collecting execution statistics will incur some overhead but in doing so I am trying to keep it minimal hence why I want to have specific aspects of each case.
I am asking this to learn how to do this in AspectJ than trying to solve a specific problem. Once I try implementing it specific problems might pop up which I can share more specific examples of that I tried and the errors or problems it created.
Sorry to write this as an answer, but it is too long for a comment.
The problem with this question is that, despite the extensive explanation, you only explain how you wish to do something technically, without even once saying what the problem is you are trying to solve. This makes the question a wonderful example of the XY problem.
What does your aspect do?
Are you running into memory or performance problems?
Are you sure that not your broad catch-all pointcut in combination with the advice code as such - in previous questions you wanted to log everything about each method execution in meticulous detail, emulating some kind of debugger - is the problem?
Are you having a problem at all? If so, you did not state it. You might just be doing premature optimisation.
You are trying to save memory and CPU cycles, I got that from your question.
Are you aware of the fact that by trying to do so you are creating many many aspect instances via per... clauses instead of using the default AspectJ singleton aspect instantiation model?
Did you measure if that makes things better and not maybe even worse?
Actually your question does not present a real problem, you are showing a hierarchy of aspects doing absolutely nothing. So the question format as such is not compatible with StackOverflow. This is a Q/A platform, not a discussion forum. Me answering by actually asking a lot instead of presenting a solution for your problem is already a symptom of it. Opinionated debates is exactly what SO is not for. So like I said before in the other questions: The best way to ask questions is to present an MCVE and a clear problem description, code others can run and reproduce your problem.
Update: As you can see in the AspectJ manual, there are the following aspect instantiation types:
singleton
per object (perthis() vs. pertarget() which is e.g. different for call() pointcuts but should be the same for execution())
per control flow (percflow() vs percflowbelow())
per type (pertypewithin(), described here)
Please note that "per control flow" is not the same as "per method". As documented, an aspect instance will be created each time a certain control flow is entered, e.g. each time a method is executed. If the same method is executed 12,345 times, then 12.345 aspect instances will be created. So if you wish to gather per-method statistics, you better store the information in the corresponding class's per-type aspect instance. For your "per call" requirement, I think a "per control flow" advice would be appropriate.
Now we are done here. Like I said, if you wish to discuss your application design ideas here, it is the wrong place. So I will stop responding here and wait for you to present concrete new questions with MCVE which can be answered clearly and correctly instead of sparking discussions. I helped as much as I could now, more than I should have because the question actually should be closed as off-topic IMO.
Good luck with your interesting project. If you need more consulting, I am also doing this as a day time job and you can hire me, of course. ;-)
Otherwise I want to encourage you to create verifiable facts by just implementing something instead of asking a whole bunch of theoretical questions here (3 of which I have answered by now) and just see if your ideas work. You seem to like to theorise. Thinking is good, but so is doing. Use both and you will make more progress and iteratively (in-)validate your ideas.

How can you give an object a value in android studio?

I am new to programming. I cannot understand most of oop. I am trying to make a custom array adapter, but I do not understand how can you assign a value to an object for example: LayoutInflater myinflater= LayoutInflater.from(getContext()); I always thought that when creating an object you use it just for the methods the class has and to call its constructor LayoutInflator myinflator = new LayoutInflator();
I hate memorizing something I do not understand and end up looking at every class that is used in tutorials but end up getting more confused. Can someone please also tell me the best way of learning Android Studio for beginners.
There are two types of classes (instantiable and static -- instantiable is the default, so there's no keyword associated). Instantiable classes can be instantiated, with new Classname(constructor,arguments,here). Static classes can't be instantiated, and usually refer to something that simply exists in the programmer's conceptual space of the program. (For example, on desktop computers, programs have an Environment that contains variables that can be set in memory before the program is started. Since there's only one Environment, it is a static class.)
There are also two types of methods (instance and static -- again, instance is the default, so there's no keyword associated). Instance methods act on data associated with an instance of the object (i.e., something that you can put in a variable of type Classname), and they need to be called with variablename.InstanceMethodName(args). Static methods, on the other hand, refer to something that is always the same across all the times you use a class, and are often called "utility methods". These are referred to by Classname.StaticMethodName(args). (Also, static classes can contain static methods, but not instance methods. This is because they can never be instantiated, so there's never any instance for instance methods to be able to operate on.)
There are some times when you don't want to use a constructor for an instantiable class. One of these times is when the processing needed to create the class can throw an exception. (It's generally considered bad form for a constructor to get into a state where it could throw.)
Looking at your example, new LayoutInflator(getContext()) could potentially throw if it's passed something that it didn't expect, or if the Context it received didn't have the correct values that it expected. So, there's a static utility method that performs the new LayoutInflator() call, and then hooks up the things that need to be hooked up and sets the values that need to be set in the new LayoutInflator instance it just constructed so that it operates properly in the context you created it in. But, because it can only do that by getting information from the Context that it's passed, it could potentially throw if it tries to access a Context member that's null at the time it accesses it.
Most books I've seen have glossed over these concepts, and I know that my explanation might be confusing for you. That's why there's a chance for multiple people to answer.
And, here's some information to help you with this site in the future. What you're looking for is a book or course on Android programming. A quick search finds https://www.onlineprogrammingbooks.com/android/ as a potential resource, but I have not vetted the quality of these books; you could potentially also find Android programming courses either online or at a local community college. Also, you're not really asking about "doing something in Android Studio", you're asking about "doing something in the language used to program Android devices, which you program with Android Studio". And finally, the last question you asked ("what is the best way to learn Android programming using Android Studio?") would generally have the entire question closed as being too basic and broad for the site ('best' is subjective, and what works for one person doesn't necessarily work for another). But, I know how confusing everything can seem, and I want you to have a good experience here. I hope that this answer helps in some small way.
Creational design patterns. LayoutInflater.from(Context) is a static method, in that static method is an invocation of a constructor. Something has to call the constructor to create an instance. But that something could be internal to the class. See also Singleton pattern.
Like #Elliott explained. it uses a Singletone Design pattern. which means that the class doesn't have any public constructors, which explains why you can't create an object from it using the new keyword.
take a look at the documentation here . notice that it has 2 protected constructors.

Constructor with many required parameters

If I have a constructor for an immutable object that requires several (4+ parameters), is having a single constructor with all the required parameters the correct approach?
I feel this becomes a candidate for the Builder pattern, but I also feel like shying away from it since the parameters are required, and a Builder seems more appropriate when you get to pick and choose.
The example in my mind is a model object that does not change once created.
If you want to create an immutable object, you have to provide a constructor with all necessary fields.
You cannot set the state partially as later you would have to add some notion of "setters" which would by definition add mutability.
Builder pattern is really about partial object building.
Both options have their drawbacks, as you suggest. A four argument constructor is hard to use correctly and makes the code hard to read. However, it communicates the intent that all parameters are mandatory.
A builder would be easier to use and make the code easier to read, but communicate the intent that the arguments are optional.
Since code is more often read than written, I recommend to use the option that promotes readability in this case. Go for a builder and make sure that all paramters are validated when the build() method is called to fail as fast as possible when using the builder incorrectly. Use javadoc to assist with communicating that all parameters are mandatory.

Why is "Set()" function better than modifying public variable?

This one is bothering me for a while now :)
Suppose we have a variable - why is writing a Set function better practice than simply modifying variable's data (and setting the variable to be public instead of private)?
It's less coding that way and I can't see any "security" issues.
Sometimes when setting a variable, you may want to do something else with the given value other than instantly place it in the class's variable: for instance, you may want to validate it or update another value that is related.
Basically, it lets the class which owns that variable control what can be done to it, and the specific series of events that occur when it is altered.
It also needs to be mentioned that it is not always better to use "set" methods. Blind compliance with patterns may lead to overcomplicated code. If class acts as just simple (really simple) data container, then public access is often acceptable. In example, look at java.awt.Rectangle or at java.awt.Point classes.
It all has to do with object orientation and how strict you are in that doctrine. If you strictly follow all the guidelines, it is bad to directly use methods and identifiers from one class, by the other. Technically there is no objection.
This discussion is the same as the static - no static discussion. The (self proclaimed) guru, found that sacrilege, but you put your computer no obstacle in the way, if you put your whole program is static.

Setting values of an object

Let's say I've got a class called House with the two fields
name
address
Each of these fields has got a getter and a setter.
Now I want another method in the House class called setValues. This method should set the fields with properties from a passed object of a different type.
There would be two ways on how to create this method. First way:
private void setHouse(HouseTransfer transer){
name = transfer.getName();
address = transfer.getAddress();
}
Or the second option:
private void setHouse(HouseTransfer transer){
setName(transfer.getName());
setAddress(transfer.getAddress());
}
Which one is more "best practice"?
At a certain level of granularity, software design is more subjective matter than one of black-and-white absolutes. I do not believe there is an absolute "best practice" here.
That being said, I personally would use the second form. The basic idea of having a setter method is that at some point you might need some some special logic around setting that value (e.g. formatting input, sanitation, validation, etc). So it makes the most sense to always rely on any such logic being in one central place, rather than scattered throughout you code anywhere this variable is set.
If you have a truly trivial example, where the setter is simply setting the value and know absolutely that no other logic will ever be added, then you could certainly use the first form for simplicity. Put there's not real performance hit to the second form, so I personally would just use that.
I would use the individual getters/setters inside of the setHouse method (which is your second option).
The fact that you have setters indicates that there is some kind of encapsulation involved around that operation. Rather than re-write the code to enforce that encapsulation, re-use what you already have.
Jon's answer to that question (Taken from another question about using getters/setters which is not a duplicate to this one)
You don't always need getters/setters, but if you have some, there's usually a good reason why you've implemented them and in that case: use them.
Perhaps if you are getting and setting in two different places you might consider factoring out your getter and setter to a common interface. This can make later customisations easier, right?

Categories