Assume I have a singleton class in an external lib to my application. But still I can
create instances of that particular class using reflection. Like this
Class clas = Class.forName(Private.class.getName());
for(Constructor c : clas.getDeclaredConstructors()){
c.setAccessible(true);
Private p = (Private) c.newInstance();
System.out.println(p);
}
How can I restrict this ? .
Thanks
J
By using a SecurityManager and controlling controlling ReflectPermission("suppressAccessChecks") (example).
The security manager impacts performances though, and it is rarely used on the server side.
See Hack any Java class using reflection attack and
How to set SecurityManager and Java security policy programmatically .
If you're talking about singletons in particular: that's one reason why the best way to implement them is via an enum:
public enum YourSingleton {
INSTANCE;
// methods go here
}
If you're talking about using setAccessible() in general: If the code is written by someone you don't trust not to do underhanded tricks like that, you shouldn't run it anyway (or run it in a sandbox). Among developers, public/private should be considered metainformation about how the code is intended to be used - not as a security feature.
Long story short: you can't.
Any constructor, public as well as private, can be accessed by reflection and can be used to instantiate a new object.
You will need to resort to other methods such as SecurityManager.
I don't think that you can restrict this.
It is obviously a dangerous/questionable practice to use reflection to access the private parts of others (snicker), but it is sometimes necessary by various types of tools and applications.
AFAIK this is sort of metaprogramming and therefore requires check on different layer of abstraction. From Javadoc I suppose, you should use SecurityManager to enforce the behaviour you want: setAccessible().
Generally IMHO you should really know what you are doing when you are metaprogramming and changing access should really have good reasons to be done.
You can do like this.
private static final Private INSTANCE = new Private();
private Private() {
if(INSTANCE !=null)
throw new IllegalStateException("Already instantiated");
}
public static Private getInstance() {
return INSTANCE;
}
Related
What is the standard approach/best practice to creating variables that are program- or package-wide in Java?
I want to set up some global variables that are accessible by multiple classes. Examples of these global variables would be things like a boolean flag testModeOn, a language setting, current local server, time display format, etc. According to some other questions (namely this one) there aren't any global variables, but there are some work-arounds using interfaces (not recommended?) or classes. Since the original poster didn't explain their situation, they got nearly every answer under the sun and I want to ask specifically for program configuration variables.
Is it better to create a class/package/interface and then import it into my working class/package? Is there anything I should be aware of when trying to implement these variables using a separate class or interface? Is there any other way to fudge package-level variables since Java apparently doesn't do this natively?
NOTE: These variables would probably not change except when the program is re-compiled.
If you're talking about constants, then they should be declared as static final fields in a class (never in an interface, according to Joshua Bloch).
If you're talking about settings which can change on the fly, then these could be either static fields in a class, or you could create a ConfigHandler class to manage the setting and fetching of configurable values.
Using class fields for mutable values might lead to concurrency problems, so if your application is multi-threaded it might be better to create a ConfigHandler class which manages concurrent access carefully and provides synchronized methods to avoid problems.
In my opinion, the best approach to passing anything into your classes is using dependency injection. This would eliminate your need for Singletons, static constants and the likes.
Depending on which DI you favor, here are some link solutions to the problem you describe:
CDI
Spring
Guice
Create a Bean class if multiple variables are required to be used in different classes. Best practice is to create a private variable with its getters and setters.
public class ListBean implements Serializable
{
private boolean testModeOn;
public boolean getTestModeOn()
{
return testModeOn;
}
public setTestModeOn(boolean testModeOn)
{
this.testModeOn = testModeOn;
}
In general there are so many ways to do it wrong regarding this topic.
The simple way is to use a Singelton.
This is not an option - Singelton is an Anti-Pattern. http://c2.com/cgi/wiki?SingletonsAreEvil
So what is else there? An Interface with public static final variables?
Not an option - Thats simply not the use case of an interface: https://stackoverflow.com/a/2659740/1248724
so what is else there?
The answer is:
What I prefer is the spring boot way (e.g. Dependency Injection)
Here an code example which is obviously Spring.
import org.springframework.stereotype.*
import org.springframework.beans.factory.annotation.*
#Component
public class MyBean {
#Value("${name}")
private String name;
// ...
}
If you are using some similar Framework such things could be easy archived.
If that is somehow not possible in your environment I had to code something like this:
public final class Configuration {
private Configuration() {
// make sure there is no instance of this class
}
public static final MySetting<DateFormat> setting = new SampleProperty();
public interface MySetting<T> {
T get();
}
private static final class SampleProperty implements MySetting<DateFormat> {
#Override
public DateFormat get() {
return new SimpleDateFormat("...");
}
}
// other inner classes that implement the MySetting interface
}
public static void main(final String[] args) {
Configuration.setting.get();
}
Benefits:
- You can validate your properties how ever you want.
- You can work with the java security manager if you like to
Downsides:
- You may have to maintain a bunch of code (this should be easier with lambda expressions)
- Not that great as the way spring offers here for example.
A very similar approach I just found: https://stackoverflow.com/a/3931399/1248724
I was prefer using static methods in my java code, since I think they are "functional""stateless" and has less side-effect. So there may be some helper classes and methods like this:
public class MyHelper {
public static Set<String> array2set(String[] items) { ... }
public static List<String> array2list(String[] items) { ...}
public static String getContentOfUrl(String url) {
// visit the url, and return the content of response
}
}
public class MyApp {
public void doSomething() {
String[] myarray = new String[]{ "aa","bb"};
Set<String> set = MyHelper.array2set(myarray);
String content = MyHelper.getContentOfUrl("http://google.com");
}
}
But my friend says we should avoid defining such static utility methods, since we call them directly in our code, it will be hard to mock them or test them if they have external dependencies. He thinks the code should be:
public class ArrayHelper {
public Set<String> array2set(String[] items) { ... }
public List<String> array2list(String[] items) { ...}
}
public class UrlHelper {
public String getContentOfUrl(String url) {
// visit the url, and return the content of response
}
}
public class MyApp {
private final ArrayHelper arrayHelper;
private final UrlHelper urlHelper;
public MyApp(ArrayHelper arrayHelper, UrlHelper urlHelper) {
this.arrayHelper = arrayHelper;
this.urlHelper = urlHelper;
}
public void doSomething() {
String[] myarray = new String[]{ "aa","bb"};
Set<String> set = arrayHelper.array2set(myarray);
String content = urlHelper.getContentOfUrl("http://google.com");
}
}
In this way, if we want to write unit tests for MyApp, we can just mock the ArrayHelper and UrlHelper and pass them to the constructor of MyApp.
I agree totally about the UrlHelper part of his opinion, since the origin static code make MyApp untestable.
But I have a little confused about the ArrayHelper part, since it doesn't depend on any external resources and the logic will be very simple. Shall we avoid using static methods at this case too?
And when to use static methods? Or just avoid using it as much as possible?
update:
We are using "TDD" in our development, so the testability of a class often is the most important concern for us.
And I just replace the word "functional" with "stateless" in the first sentence since the that's real what I meant.
You'll probably never want to mock a method that converts an array to a list (or set), and this method doesn't need any state and doesn't depend on any environment, so a static method looks fine to me.
Just like the standard Arrays.asList() (which you should probably use).
On the other hand, accessing an external URL is typically the sort of thing that you want to be able to mock easily, because not mocking it would
make the test an integration test
require to have this external URL up every time you run your tests, which you probably can't guarantee
require to have this external URL return exactly what you want it to return in your test (including errors if you want to test the event of an error).
Just beware of one disease very common amongst Java "experts": overengineering.
In your specific example, you either do or don't have a mockability issue. If you had an issue, you wouldn't be asking general questions, therefore I conclude you don't have an issue at the moment.
The general argument is that static methods are simpler and therefore the preferred choice, whenever there is a choice. A would-be instance method must first prove itself of needing to be an instance method.
If this was my project, I would defer any makeovers into instance methods until such a moment where the need for that became clear and present.
Static means you can call the method without instantiating the class. Its good if you want to package your code into a class and you have a function that just does some logic or something basic.
Just don't use a static function to try and edit member variables in the class (obviously).
Personally I think its fine to use the static function, since it is stateless.
Static methods should be used by answering the question "is this method a functionality of a specific instance?".
You shouldn't decide about a static method according to tests, you should do it according to design. Your examples doesn't need an instance because it makes no sense. So static is the better choice. You can always wrap these methods inside specific tester classes to do your tests.
The only situation in which a self-contained functionality is not static is just when you want to provide multiple implementation, so that you are forced to avoid static because you need inheritance.
I often use static methods:
for factory methods (explicitly named constructors)
to provide a functional layer above an object-oriented layer, to compose the objects
and sometimes for general-purpose functions (Apache Commons has many good examples of this)
I never use "singletons" (static objects) and methods that refer to static objects because they are a complete headache to test and reuse. I also avoid hardcoding anything into a static method that could feasibly need to be changed. Sometimes I will provide multiple methods - one with all the dependencies as parameters and others, with fewer parameters, that call the more flexible method with some default (hardcoded) values.
java.lang.Math is static which is a good example. I thought statics are not beeing garbage collected and should be avoided if possible.
No.
As mentioned by Peter Lawrey in the comment for the question, Java is all about object oriented programming. While certain functional aspects are doable and being put into eg. Java 8, at its core Java is not functional. static breaks so much of the benefits of learning how to do modern Java - not to mention all kinds of not-fun-at-all scoping problems - that there's no purpose to use them unless you're some kind of a Java wizard who really knows what happens when you use that magical keyword.
You are not a wizard. Java is not functional. If you want to be a wizard, you can learn. If you want to program in functional fashion, look into hybrid languages such as Scala or Groovy or alternatively explore the fully functional world, eg. Clojure.
I need to access a private method from another class. I have two ways of accessing it. The first is the obvious reflection. The second is sort of a hack. The private method I need to call is being called from a protected inner class's accessPrivateMethod method. This method will literally only call the private method I need. So, is it better to access it using reflection or is it better to sort of "hack" it by extending the protected inner class that calls it. See code:
method = object.getClass().getDeclaredMethod("privateMethod");
method.setAccessible(true);
Object r = method.invoke(object);
Or:
(ProtectedInnerClass is a protected inner class in the class whose private method I want to access.)
class Hack extends ProtectedInnerClass {
public void accessPrivateMethod() {
// callPrivateMethod literally only calls the private method
// I need to call.
super.callPrivateMethod();
}
}
...
Hack.accessPrivateMethod();
Some additional thoughts:
1) I've seen many people on here say to use reflection only as a last resort.
2) Reflection could cause Security issues? (SecurityManager can deny the setAccessible sometimes?) This needs to work all the time on any machine/setup.
If my hack isn't clear please say so and I will try to elaborate more. Thanks!
PS: the private method I need to access is in the JUNG libraries. Calling it fixes a bug. AKA I'm trying to find a workaround without having to edit any of the JUNG jars.
1) I've seen many people on here say to use reflection only as a last resort.
Assuming your hack actually works, it is better to use that, rather than using reflection. This is because using reflection is way more expensive.
Here's an extract on Java's API concerning reflection:
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
2) Reflection could cause Security issues? (SecurityManager can deny the setAccessible sometimes?) This needs to work all the time on any machine/setup.
Likewise:
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
So, not only the setAccessible method may be denied, but the reflection usage overall.
Another consideration is that in order to call your Hack class method without instantiation, you need to set the inner method as static.
class Hack extends ProtectedInnerClass {
public static void accessPrivateMethod() {
super.callPrivateMethod();
}
}
Hack.accessPrivateMethod();
The fact that this question rises is probably caused by bad design or the fact that Java doesn't allow "sub-package" visibility. However, if performance is a concern, go for the "little" hack. Otherwise, choose the esthetic solution using reflections. But in first place, try to find out if your design is good.
I would like to encapsulate my fields (variables), into a different file. Like getting out the logic of my application into a different file (logic.java ?), where every class could access the variables that should be "global".
Netbeans is capable of doing encapsulation, but it will just put a list of setter/getter functions into the same file.
(Later, I would like to call the functions with Logic lo = new Logic();, and lo.getValue(), for example.)
If there is a better way of doing this, please enlighten me, and I'll delete the question. (The classes are in different package. app.logic; app.desk; app.net, etc.)
What you want here are advanced refactoring capabilities, and for that I'd suggest you take a look at IntelliJ IDEA (The community edition is free to use and download and is available for all platforms).
Take a look at it here.
I don't know if I understand correctly but what you can do is implement a singleton class:
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
// members, getters and setters
}
Now this guarantees that you only have one instance of Singleton in your entire application that can be obtained anywhere with Singleton.getInstance().
i am developing a Java Api to do things (secret, uhhhh ;).
Is there a way to hide classes, and the internal structure of my API?
What i found until now:
Using inner classes (ugly way, i do not want to put all in on class file)
All classes in one package so that i can use the "package"-visibilty (also ugly, i need more packages)
Example:
---
package net.my.app;
//this is the Public Access
class MyPublicClass{
public void somePublicFunction(){
//access to not visibil classes
}
}
---
package net.my.app.notvisible:
//this is what i want to hide
class MyNOTPublicClass{
...
}
---
Any ideas?
Thank you!
There are two solutions to your question that don't involve keeping all classes in the same package.
The first is to use the Friend Accessor/Friend Package pattern described in (Practical API Design, Tulach 2008).
The second is to use OSGi.
Related Questions: 1, 2, 3, and 4.
Use interfaces to define what your
app does
Create a main entry point to accesses services, returning interfaces only
I wouldn't bother about actually hiding the implementation classes. You can never really hide them in Java, and those who are technically interested might just start your app with a debugger. Just provide no public constructors, for example
Regarding this comment:
Sean, would you elaborate a little
more on your answer? ...
One way to implement my second bullet point I mean using a Service Lookup class, e.g.
public class Lookup {
private static final Foo foo = new FooImpl();
public static Foo getFoo() {
return foo;
}
}
Foo is an interface, FooImpl an implementation class (which can be package private if you want to enforce that it can't be instantiated by clients)
What do you mean by 'hide'?
You can use the final modifier to stop people from extending methods and classes you don't want them to extend. If you want to stop people from decompiling your code, you can use code obfuscation and if you want to take it even further, you can use anonymous inner classes that implement interfaces.
You can try and make only your interfaces public. Have a look at the Factory Pattern.
Alternatively, you can implement you're application in OSGI.
Neither of these methods would allow you to hide the implementation completely to someone who really wanted to see it. Someone could still use a decompiler to examine you .class files, or even examine the code in memory.
If you really need to protect your implementation in this way, then a good approach would be to only allow access to your application as a remote service and host it on a secure machine.