Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I was looking at some code today and I came across a piece of code using reflection to take a generic object and do different things with it based on the the type. I have never seen anything like this before, and I am wondering what are the pros and cons to using reflection in java?
There are no pros or cons of reflection in Java. It's a tool which you should use in a specific situation. For example:
When you create a library which needs runtime manipulation with code.
When you have compiled jar without source code and author of jar made a mistake and didn't expose proper API.
So basically there is even no question should you use or not use reflection, it's a matter of situation. You should NOT use reflection if it possible to do the job without using it in 99.99% of cases.
UPD
Couldn't you use it for everything though? Like if you were a really big jerk you could use it to invoke every method you call, so what is stopping you from just doing that?
Mostly slowness, unmaintainable code, losing of compile time code check, breaking of encapsulation.
using reflection to take a generic object and do different things with
it based on the the type
In general, this is usually a bad idea, for reasons of performance, clarity, and robustness.
It throws away the advantages of a static type system; if you pass in types that the reflection code doesn't handle then you will get runtime errors rather than compile-time errors. If one of the classes changes implementation (e.g. renaming a method) then this will also not be detected at compile time.
If these various types have something in common, then it is usually better to handle this using polymorphism: abstract out the commonality into an interface or abstract class; each subclass can then implement the specific behaviour it needs, without other code needing to poke into the internals using reflection.
If these various types don't have anything in common, then why are they being handled together?
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
Improve this question
I've read this post which does the bytecode instrumentation in a "line by line" approach. It's clumsy and bug-prone. I wonder if Javassit supports "replacing" or "swapping" a class with an instrumented class. I see the redefineClasses method but I'm not sure it's used for that purposes, plus I can't find any examples around that.
I appreciate if anyone in SO can give me an example on using redefineClasses in Javassist
My goal is to use Java instrumentation to extract some meaningful data inside multiple Java classes and methods, much more than just printing start/end time in those examples. That's why I think "swapping a Java class" approach is more efficient during development.
What do you guys think and recommend? Thank you.
Questions not presenting any of your own code but asking others for complete sample code or other resources are likely to be closed as off-topic. At the time of writing this, your question already attracted 2 of 3 necessary close votes. Please remember what I told you in your other question about how to ask good questions and how an MCVE helps you do that.
Because you are new to Java instrumentation, I want to elaborate a little more on Johannes' correct comments: I recommend you to not just read the Baeldung article but also some related javadocs.
For example, the Java 8 API documentation for Instrumentation.redefineClasses clearly states the limitations when redefining classes:
The redefinition may change method bodies, the constant pool and attributes. The redefinition must not add, remove or rename fields or methods, change the signatures of methods, or change inheritance. These restrictions maybe be lifted in future versions.
Alas, the restrictions have not been lifted as of Java 17. The same method is described there as follows:
The supported class file changes are described in JVM TI RedefineClasses.
The document pointed to basically says the same as the Java 8 documentation, only in some more detail:
The redefinition may change method bodies, the constant pool and attributes (unless explicitly prohibited). The redefinition must not add, remove or rename fields or methods, change the signatures of methods, change modifiers, or change inheritance. The redefinition must not change the NestHost, NestMembers, Record, or PermittedSubclasses attributes. These restrictions may be lifted in future versions.
Besides, the very same restrictions apply to Instrumentation.retransformClasses, the difference basically being that you do not start from scratch there but use existing class bytes as an input and can chain multiple transformers in order to incrementally instrument your existing class. But even with redefinition, the base line stays the original class, if it was loaded before.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
My question is how mocks objects are created not how to create a mock object using a library.
I have looked at the Mockito library source code but I didn't understand how its done. I have searched in the Internet but the articles explain what are mock object and how to create them using libraries.
For dynamic programming language perhaps it's simple as we can change methods, variable but how its done in static programming language (Java for example)
Let's begin with what a mock is: an object that you can set expectancies on it regarding methods that expects to be called, and/or parameters on those methods and/or count of calls on those methods.
Mocks are sent to tested objects in order to mimic certain dependencies without having to use the real code (in many cases this is problematic/dangerous, like dealing with payment gateways).
Since mocks will need to intercept calls to all (or some, in case of partial mocks) methods, there are several ways they can be implemented, depending mainly on the features the language provides. Particularly in Java this can be implemented via proxy classes: https://stackoverflow.com/a/1082869/1974224, an approach that kinda forces you (but in a good way) to use interfaces in your code when relying on dependencies.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Recently I am working on an applications (in Java and C#, but I think the problem is not closed to those languages) where I use a few container classes (which responsibilities are storing data in a proper order) and services being method packages, operating on data stored in container classes. All of the classes mentioned above should have only one copy existing in memory, and all of them are expected to be in the memory for the whole time the application is running.
I used to think that a singleton is a good idea here, as I am sure there is only one instance of each class, so it meets my expectations. However, I learned that the Singleton pattern is deprecated, as it hides dependencies and so on. Then I heard that for such usage (always available container class or method package) static classes may be a good idea. On the other hand I recently looked at a few projects where people refused to use any static stuff, as if it was an awful practice to do so.
My question is simple (at least in its formula): are static classes a good idea for creating always available, easy to hanlde containers and method packages? If not, what should I use instead (if not singletons)?
You don't really say where the data comes from. If the data is static, then a static class is a fine solution. For example, I could envision a static class to represent the 50 US states.
In contrast, for a class that represents a list of authorized users, I would use a singleton pattern. Although there is only 1 list, that list could change while the app is running.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Reflection breaks the Encapsulation principle.
Can we protect encapsulation principle being break from reflection? Is there any API through which we can protect encapsulation from reflection ?
Technically, yes. A quick search on SO gives an example of preventing Reflection: https://stackoverflow.com/a/770672/2372767. However saying,
Reflection breaks the Encapsulation principle...
implies a misunderstanding of the principle. The point of Encapsulation is not to protect your code from malicious other code, or protect your implementation, or even create some level of security.
When you make an interface (class, module, object, etc.) with public and private methods, you're actually making two interfaces: one that is easy to use, and one that isn't. Essentially, when you make something private, what you're really saying is "this is part of the messy, complicated details of getting something done, and it may be dangerous to call this directly."
The point I want to drive home is this: your private interface is still an interface, and should be treated with the same care as your public methods. While you should never encourage another programmer to use private members, you don't know when someone else is going to need to use one of those messy, complicated steps.
As other users have mentioned, there are other ways to get a private class members. Reflection is an easy-to-use API to accomplish the same task.
On of many definitions of encapsulations says this A language mechanism for restricting access to some of the object's components. You use this mechanism while you design your application. It was never a task for it to secure the application anyway. Therefore you may not use this concept as a secure mechanism and you for sure may not claim that Reflection brakes it. Only developer may brake the reflection by leaving something not encapsulated.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
If you are familiar with the Java RDF and OWL engine Jena, then you have run across their philosophy that everything should be specified as an interface when possible. This means that a Resource, Statement, RDFNode, Property, and even the RDF Model, etc., are, contrary to what you might first think, Interfaces instead of concrete classes.
This leads to the use of Factories quite often. Since you can't instantiate a Property or Model, you must have something else do it for you -- the Factory design pattern.
My question, then, is, what is the reasoning behind using this pattern as opposed to a traditional class hierarchy system given the nature of the content the library aims to serve? It is often perfectly viable to use either one. For example, if I want a memory backed Model instead of a database-backed Model I could just instantiate those classes, I don't need to ask a Factory to give me one.
As an aside, I'm in the process of writing a library for manipulating Pearltrees data, which is exported from their website in the form of an RDF/XML document. As I write this library, I have many options for defining the relationships present in the Peartrees data. What is nice about the Pearltrees data is that it has a very logical class system: A tree is made up of pearls, which can be either Page, Reference, Alias, or Root pearls.
My question comes from trying to figure out if I should adopt the Jena philosophy in my library which uses Jena, or if I should disregard it, pick my own design philosophy, and stick with it.