Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
anti-pattern : there must be at least two key elements present to formally distinguish an actual anti-pattern from a simple bad habit, bad practice, or bad idea: Some repeated pattern of action, process or structure that initially appears to be beneficial, but ultimately produces more bad consequences than beneficial results, and A refactored solution that is clearly documented, proven in act...
So after a few hours of workaround the limitation of Reflection being currently disabled on the Google App Engine, I was wondering if someone could help me understand why object reflection can be a threat. Is it because I can inspect the private variables of a class or are there any other deeper reasons?
There are different opinions on the meaningfulness of testing of private methods, e.g., here and here. I personally think it makes sense, the question is how to do it properly. In C++ you can use a #define hack or make the test class friend, in C# there's the InternalsVisibleToAttribute, but in Java we either have to use reflection or to make them "visible for testing" and annotate them as such...
This is a question I was asked in an interview: I have class A with private members and Class B extends A. I know private members of a class cannot be accessed, but the question is: I need to access private members of class A from class B, rather than create variables with the same value in class B. I hope I am clear with this question. Thanks.
I have the code of a simple game, where an AgentInterface must be implemented in order to create an agent controller for one of the characters in the game. GameState is a class the implements GameStateInterface, and an object that implements this interface can be passed to the agent, so the agent can read and analyze the data from game state, and the agent must return the appropriate action (re...
As you know, Spring can inject values to private instance variables, and Hibernate can access private variables of persistent classes. However, I can't even call protected methods of a class through reflection! How can Spring and Hibernate blatantly breach security like that? And more importantly, how do I do it? :D
I came across an example of @Autowired public class EmpManager { @Autowired private EmpDao empDao; } I was curious about how the empDao get sets since there are no setter methods and it is private.
I saw this question http://stackoverflow.com/questions/2021716/inject-into-private-package-or-public-field-or-provide-a-setter about how to manually inject into annotated private fields (The way is adding setters or through a constructor) But, the point is how do an application server (like glassfish, axis2, jboss, ...) is able to inject into a final private field (without adding setters or ...
this was an interview question posed to me..I vaguely answered it uses Java reflections..but I was not sure. how does that work?
In Java, when a SecurityManager exists that rejects access check suppression, Constructor's newInstance method works while Class's newInstance throws a SecurityException. Here's an example: import java.lang.reflect.ReflectPermission; import java.security.Permission; public class Test { public static void main(String[] args) throws Exception { System.setSecurityManager(new Security...
I have a situation where a user's code is throwing an IllegalAccessException on a field accessed by reflection. Just before accessing the field, setAccessible(true) is called. So, it would seem to me that this method is silently failing. Under what situations would this happen? Could this have something to do with a security manager? Here is the code snippet that is causing the exception:...
I have a question about reflection I am trying to have some kind of eval() method. So i can call for example: eval("test('woohoo')"); Now I understand the there is no eval method in java but there is reflection. I made the following code: String s = "test"; Class cl = Class.forName("Main"); Method method = cl.getMethod(s, String.class); method.invoke(null, "woohoo"); This works perfectly...
public class MyClass { ClassABC abc = new ClassABC(); } I just have a .class file of ClassABC. I want to print all the public, private, protected and default field values of "abc" object. How can I do this using Reflection?
how can i set a field in a class that it's name is dynamic and stored in a string variable ? public class test { public String a1; public string a2; public test(String key) { this.key='found'; <--- error } }
Let's say we have a class foo which has a private instance variable bar. Now let us have another class, baz, which extends foo. Can non-static methods in baz access foo's variable bar if there is no accessor method defined in foo? I'm working in Java, by the way.
I was trying to fetch the value of an static private attribute via reflection, but it fails with an error. Class class = home.Student.class; Field field = studentClass.getDeclaredField("nstance"); Object obj = field.get(null); The exception i get is something like this. java.lang.IllegalAccessException: Class com.test.ReflectionTest can not access a member of class home.Student with modifie...
Something like this: class C { typeof(this) foo() { return this; } } Well, I know it's impossible in Java 6, so I'll be glad to hear if I can do it in Java 7. EDIT This should be useful for chaining method calls, and avoid to create temporary local variables, like this: class Entity { typeof(this) refresh(); typeof(this) clone(); typeof(this) detach(); } class FooEn...
Possible Duplicate: How to convert a Java object (bean) to key-value pairs (and vice versa)? What is the best way to convert a List<POJO> to a List<Map<K,V>>. Is there a custom method/ API? K = field name of the POJO and V is the corresponding value public class POJO implements Serializable{ String name; String age; //getters and setters }
Via reflection I have found a lists of properties from x POJO classes which I need to display and also created a list of headings for which I will display the properties under(headings are from annotations on the fields). The form of the POJO is that for each property I wish to display there is a getter. Here are the details: The POJO's are annotated with @Entity, I am executing a query (...
HTTPUrlConnection.setContentHandlerFactory()method throws Exception saying factory is already defined. I understand that. Is it possible to unset the factory and change the contenthandler factory?
Greetings, I understand that this is not the best forum for getting legal advices. But I am still wondering if anybody has some experience around this topic, or can point me to relevant resources that explain it. I have tried to search it online but could not find clear answers. Assuming I am using a Java open-source library from "somecompany", specifically its entities in the "org.somecompan...
  /*
   * Copyright 1997-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.lang.reflect;
 
The AccessibleObject class is the base class for Field, Method and Constructor objects. It provides the ability to flag a reflected object as suppressing default Java language access control checks when it is used. The access checks--for public, default (package) access, protected, and private members--are performed when Fields, Methods or Constructors are used to set or get fields, to invoke methods, or to create and initialize new instances of classes, respectively.

Setting the accessible flag in a reflected object permits sophisticated applications with sufficient privilege, such as Java Object Serialization or other persistence mechanisms, to manipulate objects in a manner that would normally be prohibited.

 
 public class AccessibleObject implements AnnotatedElement {

    
The Permission object that is used to check whether a client has sufficient privilege to defeat Java language access control checks.
 
     static final private java.security.Permission ACCESS_PERMISSION =
         new ReflectPermission("suppressAccessChecks");

    
Convenience method to set the accessible flag for an array of objects with a single security check (for efficiency).

First, if there is a security manager, its checkPermission method is called with a ReflectPermission("suppressAccessChecks") permission.

A SecurityException is raised if flag is true but accessibility of any of the elements of the input array may not be changed (for example, if the element object is a Constructor object for the class java.lang.Class). In the event of such a SecurityException, the accessibility of objects is set to flag for array elements upto (and excluding) the element for which the exception occurred; the accessibility of elements beyond (and including) the element for which the exception occurred is unchanged.

Parameters:
array the array of AccessibleObjects
flag the new value for the accessible flag in each object
Throws:
java.lang.SecurityException if the request is denied.
See also:
java.lang.SecurityManager.checkPermission(java.security.Permission)
java.lang.RuntimePermission
 
     public static void setAccessible(AccessibleObject[] arrayboolean flag)
         throws SecurityException {
         SecurityManager sm = System.getSecurityManager();
         if (sm != nullsm.checkPermission();
         for (int i = 0; i < array.lengthi++) {
             setAccessible0(array[i], flag);
         }
     }

    
Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks.

First, if there is a security manager, its checkPermission method is called with a ReflectPermission("suppressAccessChecks") permission.

A SecurityException is raised if flag is true but accessibility of this object may not be changed (for example, if this element object is a Constructor object for the class java.lang.Class).

A SecurityException is raised if this object is a Constructor object for the class java.lang.Class, and flag is true.

Parameters:
flag the new value for the accessible flag
Throws:
java.lang.SecurityException if the request is denied.
See also:
java.lang.SecurityManager.checkPermission(java.security.Permission)
java.lang.RuntimePermission
    public void setAccessible(boolean flagthrows SecurityException {
        SecurityManager sm = System.getSecurityManager();
        if (sm != nullsm.checkPermission();
        setAccessible0(thisflag);
    }
    /* Check that you aren't exposing java.lang.Class.<init>. */
    private static void setAccessible0(AccessibleObject objboolean flag)
        throws SecurityException
    {
        if (obj instanceof Constructor && flag == true) {
            Constructor c = (Constructor)obj;
            if (c.getDeclaringClass() == Class.class) {
                throw new SecurityException("Can not make a java.lang.Class" +
                                            " constructor accessible");
            }
        }
        obj.override = flag;
    }

    
Get the value of the accessible flag for this object.

Returns:
the value of the object's accessible flag
    public boolean isAccessible() {
        return ;
    }

    
Constructor: only used by the Java Virtual Machine.
    protected AccessibleObject() {}
    // Indicates whether language-level access checks are overridden
    // by this object. Initializes to "false". This field is used by
    // Field, Method, and Constructor.
    //
    // NOTE: for security purposes, this field must not be visible
    // outside this package.
    boolean override;
    // Reflection factory used by subclasses for creating field,
    // method, and constructor accessors. Note that this is called
    // very early in the bootstrapping process.
        AccessController.doPrivileged
            (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());

    
    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
        throw new AssertionError("All subclasses should override this method");
    }

    
    public boolean isAnnotationPresent(
        Class<? extends AnnotationannotationClass) {
        return getAnnotation(annotationClass) != null;
    }

    

Since:
1.5
    public Annotation[] getAnnotations() {
        return getDeclaredAnnotations();
    }

    

Since:
1.5
    public Annotation[] getDeclaredAnnotations()  {
        throw new AssertionError("All subclasses should override this method");
    }
New to GrepCode? Check out our FAQ X