Accessing private fields from an subclass whoes parent is abstract.

I seem not to be able to access some private fields from a subclass who's parent is abstract...
here is some code to demonstrate this: (based on yawmark's code)
import java.lang.reflect.*;
import java.net.URLClassLoader;
import java.io.*;
import java.net.*;
class PrivateReflection {
    public static void main(String[] args) throws Exception {
        Private p = new Private();
        File f=new File("test.jar");
        URL[] urls=new URL[1];
        urls[0]=f.toURL();
        URLClassLoader loader=new URLClassLoader(urls);
        Class c=loader.getClass();
//        Class c=p.getClass();
        Field field = c.getField("packages");
        field.setAccessible(true);
        System.out.println(field.get(p));
class Private {
    private String packages = "Can't get to me!";
    private void privateMethod() {
        System.out.println("The password is swordfish");
}There is no need for a test.jar file to be created.
I know for a fact that the ClassLoader abstract class defines a field called "packages" which is an HashMap.
How do i access this private field?
I am in the process of making a utility which re-compresses a inputed JAR using other compression methods than normal zip compression while still keeping the same functionality as the inputed JAR.
I do have it working for Executable JARS: www.geocities.com/budgetanime/bJAR.html
This old version only works for executable JARs and uses Bzip2 compression.
I believe i have been able to solve all but one last problem to making re-compressed JARs which work as "library" JARs. This last problem is "removing" temporary prototype classes from the system loader and replacing them with the actual decompressed classes. As there seems not to be an nice way to do this i will have to manually remove references of the classes from the system class loader which is why i am asking this question.

lol! i have solved my problem... it was because i was using the getField() method instead of the getDeclaredField() method.

Similar Messages

  • How to get private fields from super class?

    Hi.
    I must get protected and private fields from a class. I know that sounds werid but I have a very good reason for doing so, ask if you want.
    I have tried the getDeclaredField(String) method, but it apparently doesn't return the fields declared by the super classes.
    What's the smartest solution to this?
    Thank you all.
    edit: note that the superclass hierarchy's length is 3 and that there are several classes at the bottom level.
    Edited by: bestam on Sep 24, 2009 2:05 PM

    bestam wrote:
    I do not claim I have invented a new programming language Sir, you must be mistaken. This is not turing complete.
    This is a language for describing Cards or a game's rules if you want.
    AspectJ isn't Turing complete but AspectJ is still a compiler.
    This is how I have been working :
    - I have implemented the core library in Java (what is a Player, what is an Effect, what is a Card, what is a BuildingCard, what is a Player's Turn and so on)
    - It also includes packages dedicated to service, able to retrieve and send data to the clients via sockets.
    - Then I have "hardcoded" a dozen of specific cards in Java, for testing and validating the core library. I have been doing so by extending the BuildinCard's class for example.
    - But my ultimate goal is not to code thoses 1.000+ cards of the game in Java. I chosed to design a little language so that I would end up writing cards faster. While I'm traversing the syntactical tree representing the card, I feed the card's fields one by one. Some of them are quite primitive, some other are more complex and have a recursive nature for instance.
    Providing detail for how you implemented it doesn't change anything about what I already said.
    Thus, this is not really a compiler as it doesn't transform a text in language A into a text in language B.
    You really need to understand more about what "compilers" and certainly compiler theory do before you decide what they can and cannot do.
    And your statement still does not change what I said.
    Is this wrose than the bean design pattern from JSP ? I'm not sure.
    Bean design? A "bean" has almost zero requirements.
    Aside of that, it's a bit harsh to be told "read the fucking manual" while I have written my first compiler some years ago.Not sure who that was directed. I suggested some reading material on compiler theory.
    If you think that your idea is ideal then knock yourself out. Since I doubt I will end up seeing it in anything that I must maintain it doesn't matter to me. But you did in fact ask what the best solution was.

  • Accessing private field of Derived object in Base class

    Hi,
    I have this piece of code I wrote a while ago to test something. The issue is accessing a private field of Base class in Base but of a Derived object.
    Here is the code:
    class Base
         private int x;
         public int getX()
              return x;
         public int getX(Derived d)
              // return d.x;
              return ((Base) d).x;
    }The commented code does not work but casting d to Base does.
    Can someone please explain the reasoning for this.
    Forgot to mention that the compilation error is that x has private access in Base.
    Thank you.
    Edited by: 953012 on Apr 1, 2013 8:42 AM

    >
    As I understand the explanation says that you can access any private member within the code of the class that encloses the private member. So in this case x is the private member and the line of code (return d.x) is in Base which encloses the private member. Does it have to do with the fact that the Derived class does not in fact inherit the private members of Base?
    >
    It has to do with the entire quote from the spec
    >
    A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. It is not inherited by subclasses
    >
    Your code is
    public int getX(Derived d)
              // return d.x;
              return ((Base) d).x;
         }The 'Derived' class is NOT 'the top level class that encloses the declaration of the member'. It does NOT inherit 'x' which is a private member of 'Base'. As far as the 'Derived' class is concerned 'x' does not exist.
    >
    If outside Base code I have Derived d = new Derived() and I call d.getX() then isn't that like calling d.x in myX()?
    >
    How is that the same? 'Base' owns 'x' and can do whatever it wants with it. 'Derived' has no knowledge of 'x' and CAN NOT access it.

  • Accessing java fields from c++

    I have created a JNI app that needs to access the fields of the java object but when I try to access them I get an error message saying "no such field."
    When I created my header file with javah I got (JNIEnv *, jclass and jobject) as my parameter list not JNIEnv * and jobject like all the documentation does.
    then i try to access the fields with :
    fidZone = env->GetFieldID(cls, "zone","I");
    which generates the error mentioned.
    Any suggestions will be greatly appreciated.
    Cheers.

    1. Here is the native code:
    #include <jni.h>
    #include <stdio.h>
    #include "worldfl.h"
    //header for external DLL I want to access
    #include "GDAit.h"
    JNIEXPORT jlong JNICALL
    Java_worldfl_TransProjectPt(JNIEnv *env, jclass cls, jobject obj)
    jfieldID fidx, fidy, fidStr, fidZone, fidTrDir;
    long zone, agd2gda, iResult = 0;
    double transX, transY, newX, newY, accX, accY;
    /* GET the X & Y values of the coords in the world file */
    cls = env->GetObjectClass(obj);
    printf("%ld\n", cls);
    if (cls != NULL)
    fidZone = env->GetFieldID(cls, "zone","I");
    fidTrDir = env->GetFieldID(cls, "agd2gda","I");
    fidx = env->GetFieldID(cls, "transX","D");
    fidy = env->GetFieldID(cls, "transY","D");
    /*fidStr = env->GetFieldID(cls, "filename","Ljava.lang.String");*/
    transX = env->GetDoubleField(obj, fidx);
    transY = env->GetDoubleField(obj, fidy);
    zone = env->GetDoubleField(obj, fidZone);
    agd2gda = env->GetDoubleField(obj, fidTrDir);
    iResult = 0;//TransProjPt("f:\\coordcalcs\\A66 National (13.09.01).gsb", agd2gda, transX, transY, zone, &newX, &newY, &accX, &accY);
    else
    printf("Class is NULL\n");
    //env->GetDoubleField(obj, fidx) = newX;
    //env->GetDoubleField(obj, fidy) = newY;
    return(iResult);
    2. Yes it is defined as static
    private native static long TransProjectPt(worldRead wr);

  • Accessing a field from a structure with out header line

    Hi Guys,
                 I am trying to assign a field from a structure type line of data to another field.
    This structure type line don't have a header line.
    here is the example.
    IT_EKKNU TYPE  MMPUR_EKKNU.
    when I use following statement..
    move IT_EKKNU-kostl to e_cekko-kostl.
    Iam getting error "IT_ENKKNU is not a structure or Internal table with header line.
    How to access the fields in structure IT_EKKNU.
    Thank U for ur time.
    Cheers
    S Kumar

    Here IT_EKKNU is an internal table without Header line.
    You can use a structure for assignment.
    DATA: IT_EKKNU TYPE MMPUR_EKKNU,
               wa_ekknu type    ekknu.
    read table it_ekknu into wa_ekknu........
    move wa_EKKNU-kostl to e_cekko-kostl.
    *modify the code for your conditions*.

  • Setting private fields from Parent class.

    Hi all, I have what seems to be a weird situation to me.
    Basically I have two classes:
    import java.lang.reflect.Field;
    public class Parent {
         protected void ensureDefaults() {
              Field[] declaredFields = getClass().getDeclaredFields();
              for (Field field : declaredFields) {
                   Object fieldValue = getDefaultValueForType(field.getType());
                   try {
                        System.out.println("defaulting field - name: " + field.getName() + " | this: " + this);
                        field.set(this, fieldValue);
                   } catch (Exception e) {
                        e.printStackTrace();
         private Object getDefaultValueForType(Class<?> type) {
              Object defaultValue = null;
              if (type.isAssignableFrom(String.class)) {
                   defaultValue = "default";
              } else if (type.isAssignableFrom(int.class)) {
                   defaultValue = -100;
              return defaultValue;
    public class Child extends Parent {
         private String name;
         private int age;
         public Child() {
              ensureDefaults();
         public String getName() {
              return name;
         public void setName(String name) {
              this.name = name;
         public int getAge() {
              return age;
         public void setAge(int age) {
              this.age = age;
    // Test Case
    import junit.framework.TestCase;
    public class ChildTest extends TestCase {
         public void testEnsureDefaults() {
              Child child = new Child();
              assertEquals("default", child.getName());
              assertEquals(-100, child.getAge());
    }The odd thing to me is that the output looks like:
    defaulting field - name: name | this: Child@7431b9
    java.lang.IllegalAccessException: Class Parent can not access a member of class Child with modifiers "private"
    ... more exception ...
    defaulting field - name: age | this: Child@7431b9
    java.lang.IllegalAccessException: Class Parent can not access a member of class Child with modifiers "private"
    ... more exception ...
    As you can see, it doesn't like me setting (or getting for that matter - tried that) these fields because they're private. However, if you look it's saying that "this" is a Child, so shouldn't those fields be accessible? Shouldn't ensureDefaults be executed as if it was being called by the Child instance?
    Obviously, I can try to use the accessor methods, but that means creating strings for method names, and then looking for the methods. I'd like to avoid this and it seems to me this should work, no?
    Another odd thing is that if I change the fields in Child to protected, it works fine.
    Also, I'm not sure if this is important (I don't know enough about security managers to know if they're different platform to platform, version to version), I'm on a Mac OSX 10.4.11 and:
    java version "1.5.0_13"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_13-b05-241)
    Java HotSpot(TM) Client VM (build 1.5.0_13-121, mixed mode, sharing)
    Any help with this would be greatly appreciated.
    Thanks,
    Eric

    jschell wrote:
    As you can see, it doesn't like me setting (or getting for that matter - tried that) these fields because they're private.Myself I don't like it because it suggests a design problem which is associated with understanding that although a child is a parent that doesn't mean that a parent is a child.
    I understand that, but I don't see how this actually breaks that. The Child is executing a method that is passed down to it from it's Parent, but it's executing it as itself - by that I mean it's not looking at anything that it can't already look at, or at least I thought it was.
    Shouldn't ensureDefaults be executed as if it was being called by the Child instance?No.Ok, I thought it was. Can you please explain this a bit more, I want to understand it.
    >
    Another odd thing is that if I change the fields in Child to protected, it works fine.If you messed with reflection some more you could get to to work even with private. How exactly? I really don't want to bypass any security measures (by settings accessible or using a different security manager, or anything like that). As I mentioned in my last post, what I want to do really is nothing more than a nice way to have a generic toString or hashCode method, if it's not possible to do it nicely - within java's default constraints, I'd rather not.
    >
    However in general the idiom would still be wrong.I'm moving more towards using beans anyway, so I plan on just calling accessor methods which corrects the "wrong idiom" right?
    Thanks for all the help,
    Eric

  • Access private variables from javascript

    Hi.
    How can i access my objects and varibles, in my java code from my javascript.

    Try displaying the value before you assign it.
    If you wanna display the value of a text field called textCallClass, this is the javascript code:
    alert(document.getElementById("form1:textCallClass").value);
    And if you wanna display a field called uniqueNum from a page called
    SchemeHolders, this is the javacsript code:
    alert(#{SchemeHolders.uniqueNum});
    You have ro have a public function called getUniqueNum in SchemeHolders.java. And ensure the case is exactly like mine is.
    That does work fine in my programs, if you have any other problems, post the error message.

  • Access required fields from another datasource

    Hi,
    I need to have contract information for Sales Orders (i.e. doc_type / doc_categ / doc_categr / refe_doc) in Billing Document ODS (source - 2lis_13_vditm).
    This data exists in my Sales Order Item ODS (source - 2lis_11_vaitm). What is the most efficient way of getting this data?
    I am considering doing a lookup in the update rules of the Billing Document ODS from the Sales Order Item ODS. Will this do the trick?
    Thanks,
    Milind

    Hi,
    I think this all fields are already present in the billing extractor.
    doc_type / doc_categ / doc_categr / refe_doc...this all attributes of sales are defenatley in the billing extractor just type to explore it...I am not sure what is reference doc...but rest three are there..and are commonly used from this data source....just try it out.
    There is something called as SD document category,Sales document type etc. present in the 2LIS_13_VDITM which contains the values for sales doc only.check for the fields like PVTYP,AUTYP etc.I dont remember it exactly the field name but its there and I have used it from 2LIS_13_VDITM...no need to look into sales extractor for this.
    also doing a look up like this will create a huge performace issues as for every billing doc loaded you will have to scan the whole sales item DSO again and again.will not advice to do that.
    Thanks
    Ajeet

  • Accessing input field from the JSP in dynpage

    HI all,
          I am trying to access the input field of the jsp page in my JSPDynpage but it is always return null.My Input is a normal HTML element not a HTMLB element
    JSP File :
         <hbj:content id="myContext" >
      <hbj:page title="PageTitle">
      <hbj:form id="myFormId" >
         <div class="content">
            <table cellpadding="2" cellspacing="2">
                        <tr>
                               <td>
                                  <label for="name"><strong>UserName:</strong></label><span id="info_name">(This field is required)</span><br />                           
                                     <input name="name" id="name" size="10" maxlength="10" type="text" />
                               </td>
                        </tr>
                        <tr>
                             <td>
                                  <label for="email"><strong>EmailID:</strong></label><span id="info_email">(This field is required)</span><br />                           
                                     <input name="email" id="email" size="20" maxlength="20" type="text" /></td>
                        </tr>\
    </Table>
    JSPDynpage:
           InputField myInputField = (InputField) getComponentByName("name");
         if (myInputField != null) {
          name = myInputField.getValueAsDataType().toString();
                   InputField myInputField1 = (InputField) getComponentByName("email");
         if (myInputField1 != null) {
          name = myInputField1.getValueAsDataType().toString();
    In both the cases myInputField and myInputField1 are null . My Question is what should be the parameter that i need to pass for getComponentByName method.
    Regards,
    Raj.

    hi,
    The way you are trying to get the input field value works good with hbj type elements.
    either you change your input field to an hbj one or use java script inside your jsp page to catch the value
    like
    for HTML:
    [HTML Input Field|http://www.w3schools.com/HTMLDOM/met_doc_getelementbyid.asp]
    and for HTMLB
    refer this link:
    [SAP HTMLB GuideLines|http://www.sapdesignguild.org/resources/htmlb_guidance/index.html]
    Regards,
    Srinu

  • Formatted search on BOM how to access variable field from matrix?

    hi,
    i have assigned a formatted search to the Quantity field on the BOM. its as follows.
    declare @width numeric (19,6)
    declare @height numeric (19,6)
    declare @lenght numeric (19,6)
    set @width = Convert(numeric(19,6), $[$3.50.92])
    set @height = Convert(numeric(19,6),$[$3.51.93])
    set @length = Convert(numeric(19,9),$[$3.52.91])
    SELECT @width * @height * @length
    but when its executing i am getting internal error.
    Thanks in Advance,
    Vasu Natari.

    Hi,
    are you sure, that in @width , @height and @length is some value and not null?
    Try it as
    declare @width numeric (19,6)
    declare @height numeric (19,6)
    declare @lenght numeric (19,6)
    select @width = Convert(numeric(19,6), $http://$3.50.92)
    select @height = Convert(numeric(19,6),$http://$3.51.93)
    select @length = Convert(numeric(19,9),$http://$3.52.91)
    SELECT convert(numeric(19,6), isnull(@width,0) * isnull(@height,0) * isnull(@length,0)) as result
    Petr

  • Accessing input/ouyput field from report

    Hi All,
    I have one input/output field in the Screen painter.
    But when i am accessing the field from the PAI i am getting a syntax error saying that the field is unknown .
    Please give your help regarding this.
    Thanks in Advance.

    Hi Mayank Verma,
    You should declare the variable with the same name as it's in Screen Painter for that Input/Output field with the associated Dictionary type..
    Once you will declare it the screen will pass the data you entered in screen to the varible you declared in your program..
    Hope it will solve your problem..
    Thanks & Regards
    ilesh 24x7
    ilesh Nandaniya

  • Problem with accessing init parameters from JSP file

    Hi,
    I have my init parameters and Jsp configured in web.xml
    <servlet>
              <servlet-name>TestJsp</servlet-name>
              <jsp-file>/Test.jsp</jsp-file>
              <init-param>
                   <param-name>username</param-name>
                   <param-value>Balboa</param-value>
              </init-param>
    </servlet> How do I access 'username' field from JSP file.
    Kindly help.
    Thanks.

    you can do this in the jsp
    <%=config.getInitParameter("username")%>or do it in the jspInit method in the jsp:
    <%!  String userName = null; 
      public void jspInit() {   
        ServletConfig config = getServletConfig();   
        userName   = config.getInitParameter("userName ");  
    %>
    Hello <%=userName%>

  • Access metadata fields through a custom Service Class

    Hi all,
    I have to create a custom component for Oracle Content Server. I need to access metadata fields from a custom Service Class.
    Can you directly access metadata through a java class or to pass parameters (metadata fields) from a web page to java class? How?
    Are there other solutions?
    Thanks, ale

    I'm not sure if I understand exactly what you are after, but here is some information.
    If your url is http://someserver/idc/idcplg?IdcService=CUSTOM_SERVERY&Parm1=A&Parm2=B
    Then in your java code you can use the binder.getLocal method to get those values.
    String strParm1 = binder.getLocal("Parm1");
    you may have to use binder or m_binder (depends on the variable name in your specific situation).

  • Accessing a private variable from a public method of the same class

    can anyone please tell me how to access a private variable, declared in a private method from a public method of the same class?
    here is the code, i'm trying to get the variable int[][][] grids.
    public static int[][] generateS(boolean[][] constraints)
      private static int[][][] sudokuGrids()
        int[][][] grids; // array of arrays!
        grids = new int[][][]
        {

    Are you sure that you want to have everything static here? You're possibly throwing away all the object-oriented goodness that java has to offer.
    Anyway, it seems to me that you can't get to that variable because it is buried within a method -- think scoping rules. I think that if you want to get at that variable your program design may be under the weather and may benefit from a significant refactoring in an OOP-manner.
    If you need more specific help, then ask away, but give us more information please about what you are trying to accomplish here and how you want to do this. Good luck.
    Pete
    Edited by: petes1234 on Nov 16, 2007 7:51 PM

  • URGENT!Can I user a THIN jdbc driver to access a CLOB field from oracle 8.0.5 DB?

    URGENT!Can I user a THIN jdbc driver to access a CLOB field from oracle 8.0.5 DB?

    I think you'd need to contact Oracle support to get access to older versions of the driver.
    Since 8.0.5 isn't supported any longer, however, is it possible for you to update your Oracle client to one of the supported releases-- 8.1.7 or 9i?
    Justin

Maybe you are looking for