Search Results

Search found 35 results on 2 pages for 'illegalaccessexception'.

Page 1/2 | 1 2  | Next Page >

  • getting IllegalAccessException when accessing a protected method from parent from inner class

    - by EnToutCas
    I got a very weird problem and a weird solution: class Parent { protected void aProtectedMethod() { doSomething(); } } class Child extends Parent { void anotherMethod() { new SomeInterface() { public void interfaceMethod() { aProtectedMethod(); } }; } } When child.anotherMethod() is run, I got IllegalAccessException at myProtectedMethod(), saying my inner class doesn't have access to the Parent class... However, if I add: protected void aProtectedMethod() { super.aProtectedMethod(); } in my Child class, everything is fine... I wonder why this is?

    Read the article

  • Java Reflection, java.lang.IllegalAccessException Error

    - by rubby
    Hi all, My goal is : Third class will read the name of the class as String from console.Upon reading the name of the class, it will automatically and dynamically (!) generate that class and call its writeout method. If that class is not read from input, it will not be initialized. And I am taking java.lang.IllegalAccessException: Class deneme.class3 can not access a member of class java.lang.Object with modifiers "protected" error. And i don't know how i can fix it.. Can anyone help me? import java.io.*; import java.lang.reflect.*; class class3 { public void run() { try { BufferedReader reader= new BufferedReader(new InputStreamReader(System.in)); String line=reader.readLine(); Class c1 = Class.forName("java.lang.String"); Object obj = new Object(); Class c2 = obj.getClass(); Method writeout = null; for( Method mth : c2.getDeclaredMethods() ) { writeout = mth; break; } Object o = c2.newInstance(); writeout.invoke( o ); } catch(Exception ee) { System.out.println("ERROR! "+ee); } } public void writeout3() { System.out.println("class3"); } } class class4 { public void writeout4() { System.out.println("class4"); } } class ornek { public static void main(String[] args) { System.out.println("Please Enter Name of Class : "); class3 example = new class3(); example.run(); } }

    Read the article

  • java.lang.IllegalAccessException during Ant jwsc webservice build

    - by KevB
    Hi. I have a large application, part of which relies on a set of 3 webservices. I'm currently in the process of writing an Ant build script to build and package the application into an EAR file. When building the web sub-project for this application I use the <jwsc> task in Ant to compile the webservices. This causes an IllegalAccessException, as outlined in the stack trace below: [jwsc] warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds [jwsc] JWS: processing module weboutput [jwsc] Parsing source files [jwsc] Parsing source files [jwsc] 3 JWS files being processed for module weboutput [jwsc] JWS: C:\dev\ir\irWeb\src\webservices\DailyRun.java Validated. [jwsc] JWS: C:\dev\ir\irWeb\src\webservices\PendingRegistrationsSweep.java Validated. [jwsc] JWS: C:\dev\ir\irWeb\src\webservices\RegistrationsGoLive.java Validated. [jwsc] Compiling 6 source files to C:\DOCUME~1\KEVIN~1.BRE\LOCALS~1\Temp\_5l950r [jwsc] An exception has occurred in the compiler (1.6.0_23). Please file a bug at the Java Developer Connection (http://java.sun.com/webapps/bugreport) after checking the Bug Parade for duplicates. Include your program and the following diagnostic in your report. Thank you. [jwsc] java.lang.IllegalAccessError: tried to access class com.sun.tools.javac.jvm.ClassReader$AnnotationDefaultCompleter from class com.sun.tools.javac.jvm.ClassReader [jwsc] at com.sun.tools.javac.jvm.ClassReader.attachAnnotationDefault(ClassReader.java:1128) [jwsc] at com.sun.tools.javac.jvm.ClassReader.readMemberAttr(ClassReader.java:906) [jwsc] at com.sun.tools.javac.jvm.ClassReader.readMemberAttrs(ClassReader.java:1027) [jwsc] at com.sun.tools.javac.jvm.ClassReader.readMethod(ClassReader.java:1490) [jwsc] at com.sun.tools.javac.jvm.ClassReader.readClass(ClassReader.java:1586) [jwsc] at com.sun.tools.javac.jvm.ClassReader.readClassFile(ClassReader.java:1658) [jwsc] at com.sun.tools.javac.jvm.ClassReader.fillIn(ClassReader.java:1845) [jwsc] at com.sun.tools.javac.jvm.ClassReader.complete(ClassReader.java:1777) [jwsc] at com.sun.tools.javac.code.Symbol.complete(Symbol.java:386) [jwsc] at com.sun.tools.javac.code.Symbol$ClassSymbol.complete(Symbol.java:763) [jwsc] at com.sun.tools.javac.jvm.ClassReader.loadClass(ClassReader.java:1951) [jwsc] at com.sun.tools.javac.comp.Resolve.loadClass(Resolve.java:842) [jwsc] at com.sun.tools.javac.comp.Resolve.findIdentInPackage(Resolve.java:1011) [jwsc] at com.sun.tools.javac.comp.Attr.selectSym(Attr.java:1921) [jwsc] at com.sun.tools.javac.comp.Attr.visitSelect(Attr.java:1835) [jwsc] at com.sun.tools.javac.tree.JCTree$JCFieldAccess.accept(JCTree.java:1522) [jwsc] at com.sun.tools.javac.comp.Attr.attribTree(Attr.java:360) [jwsc] at com.sun.tools.javac.comp.Attr.attribType(Attr.java:390) [jwsc] at com.sun.tools.javac.comp.MemberEnter.attribImportType(MemberEnter.java:681) [jwsc] at com.sun.tools.javac.comp.MemberEnter.visitImport(MemberEnter.java:545) [jwsc] at com.sun.tools.javac.tree.JCTree$JCImport.accept(JCTree.java:495) [jwsc] at com.sun.tools.javac.comp.MemberEnter.memberEnter(MemberEnter.java:387) [jwsc] at com.sun.tools.javac.comp.MemberEnter.memberEnter(MemberEnter.java:399) [jwsc] at com.sun.tools.javac.comp.MemberEnter.visitTopLevel(MemberEnter.java:512) [jwsc] at com.sun.tools.javac.tree.JCTree$JCCompilationUnit.accept(JCTree.java:446) [jwsc] at com.sun.tools.javac.comp.MemberEnter.memberEnter(MemberEnter.java:387) [jwsc] at com.sun.tools.javac.comp.MemberEnter.complete(MemberEnter.java:819) [jwsc] at com.sun.tools.javac.code.Symbol.complete(Symbol.java:386) [jwsc] at com.sun.tools.javac.code.Symbol$ClassSymbol.complete(Symbol.java:763) [jwsc] at com.sun.tools.javac.comp.Enter.complete(Enter.java:464) [jwsc] at com.sun.tools.javac.comp.Enter.main(Enter.java:442) [jwsc] at com.sun.tools.javac.main.JavaCompiler.enterTrees(JavaCompiler.java:819) [jwsc] at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:727) [jwsc] at com.sun.tools.javac.main.Main.compile(Main.java:353) [jwsc] at com.sun.tools.javac.main.Main.compile(Main.java:279) [jwsc] at com.sun.tools.javac.main.Main.compile(Main.java:270) [jwsc] at com.sun.tools.javac.Main.compile(Main.java:69) [jwsc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [jwsc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.taskdefs.compilers.Javac13.execute(Javac13.java:56) [jwsc] at org.apache.tools.ant.taskdefs.Javac.compile(Javac.java:1097) [jwsc] at weblogic.wsee.tools.anttasks.DelegatingJavacTask$ExposingJavac.compile(DelegatingJavacTask.java:343) [jwsc] at weblogic.wsee.tools.anttasks.DelegatingJavacTask.compile(DelegatingJavacTask.java:286) [jwsc] at weblogic.wsee.tools.anttasks.JwscTask.javac(JwscTask.java:335) [jwsc] at weblogic.wsee.tools.anttasks.JwsModule.compile(JwsModule.java:390) [jwsc] at weblogic.wsee.tools.anttasks.JwsModule.build(JwsModule.java:262) [jwsc] at weblogic.wsee.tools.anttasks.JwscTask.execute(JwscTask.java:227) [jwsc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [jwsc] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.Task.perform(Task.java:348) [jwsc] at org.apache.tools.ant.Target.execute(Target.java:390) [jwsc] at org.apache.tools.ant.Target.performTasks(Target.java:411) [jwsc] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1397) [jwsc] at org.apache.tools.ant.helper.SingleCheckExecutor.executeTargets(SingleCheckExecutor.java:38) [jwsc] at org.apache.tools.ant.Project.executeTargets(Project.java:1249) [jwsc] at org.apache.tools.ant.taskdefs.Ant.execute(Ant.java:442) [jwsc] at org.apache.tools.ant.taskdefs.CallTarget.execute(CallTarget.java:105) [jwsc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [jwsc] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.Task.perform(Task.java:348) [jwsc] at org.apache.tools.ant.Target.execute(Target.java:390) [jwsc] at org.apache.tools.ant.Target.performTasks(Target.java:411) [jwsc] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1397) [jwsc] at org.apache.tools.ant.Project.executeTarget(Project.java:1366) [jwsc] at com.bea.workshop.cmdline.antlib.AntExTask.execute(AntExTask.java:406) [jwsc] at com.bea.workshop.cmdline.antlib.AntCallExTask.execute(AntCallExTask.java:118) [jwsc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [jwsc] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.Task.perform(Task.java:348) [jwsc] at org.apache.tools.ant.Target.execute(Target.java:390) [jwsc] at org.apache.tools.ant.Target.performTasks(Target.java:411) [jwsc] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1397) [jwsc] at org.apache.tools.ant.Project.executeTarget(Project.java:1366) [jwsc] at com.bea.workshop.cmdline.antlib.AntExTask.execute(AntExTask.java:406) [jwsc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [jwsc] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.Task.perform(Task.java:348) [jwsc] at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:68) [jwsc] at net.sf.antcontrib.logic.IfTask.execute(IfTask.java:217) [jwsc] at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.TaskAdapter.execute(TaskAdapter.java:154) [jwsc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [jwsc] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.Task.perform(Task.java:348) [jwsc] at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:68) [jwsc] at net.sf.antcontrib.logic.IfTask.execute(IfTask.java:197) [jwsc] at sun.reflect.GeneratedMethodAccessor44.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.TaskAdapter.execute(TaskAdapter.java:154) [jwsc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [jwsc] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.Task.perform(Task.java:348) [jwsc] at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:68) [jwsc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [jwsc] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.Task.perform(Task.java:348) [jwsc] at org.apache.tools.ant.taskdefs.MacroInstance.execute(MacroInstance.java:398) [jwsc] at net.sf.antcontrib.logic.ForTask.doSequentialIteration(ForTask.java:259) [jwsc] at net.sf.antcontrib.logic.ForTask.doToken(ForTask.java:268) [jwsc] at net.sf.antcontrib.logic.ForTask.doTheTasks(ForTask.java:299) [jwsc] at net.sf.antcontrib.logic.ForTask.execute(ForTask.java:244) [jwsc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [jwsc] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.Task.perform(Task.java:348) [jwsc] at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:68) [jwsc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [jwsc] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.Task.perform(Task.java:348) [jwsc] at org.apache.tools.ant.taskdefs.MacroInstance.execute(MacroInstance.java:398) [jwsc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [jwsc] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.Task.perform(Task.java:348) [jwsc] at org.apache.tools.ant.Target.execute(Target.java:390) [jwsc] at org.apache.tools.ant.Target.performTasks(Target.java:411) [jwsc] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1397) [jwsc] at org.apache.tools.ant.helper.SingleCheckExecutor.executeTargets(SingleCheckExecutor.java:38) [jwsc] at org.apache.tools.ant.Project.executeTargets(Project.java:1249) [jwsc] at org.apache.tools.ant.taskdefs.Ant.execute(Ant.java:442) [jwsc] at org.apache.tools.ant.taskdefs.CallTarget.execute(CallTarget.java:105) [jwsc] at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) [jwsc] at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) [jwsc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [jwsc] at java.lang.reflect.Method.invoke(Method.java:597) [jwsc] at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106) [jwsc] at org.apache.tools.ant.Task.perform(Task.java:348) [jwsc] at org.apache.tools.ant.Target.execute(Target.java:390) [jwsc] at org.apache.tools.ant.Target.performTasks(Target.java:411) [jwsc] at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1397) [jwsc] at org.apache.tools.ant.Project.executeTarget(Project.java:1366) [jwsc] at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41) [jwsc] at org.apache.tools.ant.Project.executeTargets(Project.java:1249) [jwsc] at org.apache.tools.ant.Main.runBuild(Main.java:801) [jwsc] at org.apache.tools.ant.Main.startAnt(Main.java:218) [jwsc] at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280) [jwsc] at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109) [AntUtil.deleteDir] Deleting directory C:\DOCUME~1\KEVIN~1.BRE\LOCALS~1\Temp_5l950r The Ant target that uses the <jwsc> task is this: <target name="webservice.build" depends="init,generated.root.init"> <path id="jwsc.srcpath"> <path path="${java.sourcepath}" /> <pathelement path="build/assembly/.src" /> </path> <taskdef name="jwsc" classname="weblogic.wsee.tools.anttasks.JwscTask" > <classpath> <path refid="weblogic.jar.classpath" /> </classpath> </taskdef> <property name="jwsc.module.root" value="${project.dir}/build/weboutput"/> <property name="jwsc.contextpath" value="irWeb"/> <property name="jwsc.srcpath.prop" refid="jwsc.srcpath"/> <path id="jwsc.classpath"> <path refid="weblogic.jar.classpath" /> <path refid="java.classpath" /> <pathelement path="${java.outpath}" /> </path> <jwsc destdir="${project.dir}/build" classpathref="jwsc.classpath"> <module name="weboutput" explode="true" contextPath="${jwsc.contextpath}" > <jwsFileSet srcdir="${webservices.dir}" type="JAXRPC"> <include name="**/*.java"/> </jwsFileSet> <descriptor file="${jwsc.module.root}/WEB-INF/web.xml" /> <descriptor file="${jwsc.module.root}/WEB-INF/weblogic.xml" /> </module> </jwsc> </target> I have no idea what could be causing the compiler to throw this error at build time, and a day of google searching has turned up other instances of this error caused by different triggers, and solutions for those propblems didn't work for me. I also found a single report on the Oracle forums that seemed to be a carbon copy of this issue, but there were no replies. The application is written in Weblogic Workshop 10, runs on Weblogic Server 10.3, and uses Beehive / NetUI. Not sure if that would make a difference or not though. The build scripts were automatically generated by Weblogic Workshop, with some tweaks and fixes made to other aspects of the files by myself to fix other compatability issues. I am using Java 1.6.0_23 from Sun, and Ant 1.8.1 Any help or advice would be greatly appreciated.

    Read the article

  • How to access a field's value in an object using reflection

    - by kentcdodds
    My Question: How to overcome an IllegalAccessException to access the value of a an object's field using reflection. Expansion: I'm trying to learn about reflection to make some of my projects more generic. I'm running into an IllegalAccessException when trying to call field.getValue(object) to get the value of that field in that object. I can get the name and type just fine. If I change the declaration from private to public then this works fine. But in an effort to follow the "rules" of encapsulation I don't want to do this. Any help would be greatly appreciated! Thanks! My Code: package main; import java.lang.reflect.Field; public class Tester { public static void main(String args[]) throws Exception { new Tester().reflectionTest(); } public void reflectionTest() throws Exception { Person person = new Person("John Doe", "555-123-4567", "Rover"); Field[] fields = person.getClass().getDeclaredFields(); for (Field field : fields) { System.out.println("Field Name: " + field.getName()); System.out.println("Field Type: " + field.getType()); System.out.println("Field Value: " + field.get(person)); //The line above throws: Exception in thread "main" java.lang.IllegalAccessException: Class main.Tester can not access a member of class main.Tester$Person with modifiers "private final" } } public class Person { private final String name; private final String phoneNumber; private final String dogsName; public Person(String name, String phoneNumber, String dogsName) { this.name = name; this.phoneNumber = phoneNumber; this.dogsName = dogsName; } } } The Output: run: Field Name: name Field Type: class java.lang.String Exception in thread "main" java.lang.IllegalAccessException: Class main.Tester can not access a member of class main.Tester$Person with modifiers "private final" at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:95) at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:261) at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:253) at java.lang.reflect.Field.doSecurityCheck(Field.java:983) at java.lang.reflect.Field.getFieldAccessor(Field.java:927) at java.lang.reflect.Field.get(Field.java:372) at main.Tester.reflectionTest(Tester.java:17) at main.Tester.main(Tester.java:8) Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds)

    Read the article

  • when to use the abstract factory pattern?

    - by hguser
    Hi: I want to know when we need to use the abstract factory pattern. Here is an example,I want to know if it is necessary. The UML THe above is the abstract factory pattern, it is recommended by my classmate. THe following is myown implemention. I do not think it is necessary to use the pattern. And the following is some core codes: package net; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class Test { public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { DaoRepository dr=new DaoRepository(); AbstractDao dao=dr.findDao("sql"); dao.insert(); } } class DaoRepository { Map<String, AbstractDao> daoMap=new HashMap<String, AbstractDao>(); public DaoRepository () throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException { Properties p=new Properties(); p.load(DaoRepository.class.getResourceAsStream("Test.properties")); initDaos(p); } public void initDaos(Properties p) throws InstantiationException, IllegalAccessException, ClassNotFoundException { String[] daoarray=p.getProperty("dao").split(","); for(String dao:daoarray) { AbstractDao ad=(AbstractDao)Class.forName(dao).newInstance(); daoMap.put(ad.getID(),ad); } } public AbstractDao findDao(String id) {return daoMap.get(id);} } abstract class AbstractDao { public abstract String getID(); public abstract void insert(); public abstract void update(); } class SqlDao extends AbstractDao { public SqlDao() {} public String getID() {return "sql";} public void insert() {System.out.println("sql insert");} public void update() {System.out.println("sql update");} } class AccessDao extends AbstractDao { public AccessDao() {} public String getID() {return "access";} public void insert() {System.out.println("access insert");} public void update() {System.out.println("access update");} } And the content of the Test.properties is just one line: dao=net.SqlDao,net.SqlDao So any ont can tell me if this suitation is necessary?

    Read the article

  • JSP cant find bean Class using "" modifiers

    - by Ravana
    Hey I'm using Netbeans for my IDE and I'm getting an error when I try to run my EJB program. I get an error when I declare and give the path of the class in my JSP to a bean. <jsp:useBean id="book" class="BookBean.Book" scope="application" /> <jsp:setProperty name="book" property="*" /> When I run the program I get this error javax.servlet.ServletException: java.lang.InstantiationException: class BookBean.Book : java.lang.IllegalAccessException: Class java.beans.Beans can not access a member of class BookBean.Book with modifiers "" and java.lang.InstantiationException: class BookBean.Book : java.lang.IllegalAccessException: Class java.beans.Beans can not access a member of class BookBean.Book with modifiers "" I removed the "" and put in '' to see if that works, but it doesn't. Any idea? I also put a breakpoint there and it def. is the root of the problem. Thanks.

    Read the article

  • Examples of bad variable names and reasons [on hold]

    - by user470184
    I'll start with a class in the jdk package : public final class Sdp { should be : public final class SocketsDirectProtocol { Sdp is class name, this is ambigious, should be : Class<?> cl = Class.forName("java.net.SdpSocketImpl", true, null); should be : Class<?> clazz = Class.forName("java.net.SdpSocketImpl", true, null); cl is ambiguous private static void setAccessible(final AccessibleObject o) { should be : private static void setAccessible(final AccessibleObject accessibleObject) { There are various other examples in this class, do you have similar and/or differing examples of variables that were named badly ? package com.oracle.net; public final class Sdp { private Sdp() { } /** * The package-privage ServerSocket(SocketImpl) constructor */ private static final Constructor<ServerSocket> serverSocketCtor; static { try { serverSocketCtor = (Constructor<ServerSocket>) ServerSocket.class.getDeclaredConstructor(SocketImpl.class); setAccessible(serverSocketCtor); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } /** * The package-private SdpSocketImpl() constructor */ private static final Constructor<SocketImpl> socketImplCtor; static { try { Class<?> cl = Class.forName("java.net.SdpSocketImpl", true, null); socketImplCtor = (Constructor<SocketImpl>)cl.getDeclaredConstructor(); setAccessible(socketImplCtor); } catch (ClassNotFoundException e) { throw new AssertionError(e); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } private static void setAccessible(final AccessibleObject o) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { o.setAccessible(true); return null; } }); } /** * SDP enabled Socket. */ private static class SdpSocket extends Socket { SdpSocket(SocketImpl impl) throws SocketException { super(impl); } } /** * Creates a SDP enabled SocketImpl */ private static SocketImpl createSocketImpl() { try { return socketImplCtor.newInstance(); } catch (InstantiationException x) { throw new AssertionError(x); } catch (IllegalAccessException x) { throw new AssertionError(x); } catch (InvocationTargetException x) { throw new AssertionError(x); } } /** * Creates an unconnected and unbound SDP socket. The {@code Socket} is * associated with a {@link java.net.SocketImpl} of the system-default type. * * @return a new Socket * * @throws UnsupportedOperationException * If SDP is not supported * @throws IOException * If an I/O error occurs */ public static Socket openSocket() throws IOException { SocketImpl impl = createSocketImpl(); return new SdpSocket(impl); } /** * Creates an unbound SDP server socket. The {@code ServerSocket} is * associated with a {@link java.net.SocketImpl} of the system-default type. * * @return a new ServerSocket * * @throws UnsupportedOperationException * If SDP is not supported * @throws IOException * If an I/O error occurs */ public static ServerSocket openServerSocket() throws IOException { // create ServerSocket via package-private constructor SocketImpl impl = createSocketImpl(); try { return serverSocketCtor.newInstance(impl); } catch (IllegalAccessException x) { throw new AssertionError(x); } catch (InstantiationException x) { throw new AssertionError(x); } catch (InvocationTargetException x) { Throwable cause = x.getCause(); if (cause instanceof IOException) throw (IOException)cause; if (cause instanceof RuntimeException) throw (RuntimeException)cause; throw new RuntimeException(x); } } /** * Opens a socket channel to a SDP socket. * * <p> The channel will be associated with the system-wide default * {@link java.nio.channels.spi.SelectorProvider SelectorProvider}. * * @return a new SocketChannel * * @throws UnsupportedOperationException * If SDP is not supported or not supported by the default selector * provider * @throws IOException * If an I/O error occurs. */ public static SocketChannel openSocketChannel() throws IOException { FileDescriptor fd = SdpSupport.createSocket(); return sun.nio.ch.Secrets.newSocketChannel(fd); } /** * Opens a socket channel to a SDP socket. * * <p> The channel will be associated with the system-wide default * {@link java.nio.channels.spi.SelectorProvider SelectorProvider}. * * @return a new ServerSocketChannel * * @throws UnsupportedOperationException * If SDP is not supported or not supported by the default selector * provider * @throws IOException * If an I/O error occurs */ public static ServerSocketChannel openServerSocketChannel() throws IOException { FileDescriptor fd = SdpSupport.createSocket(); return sun.nio.ch.Secrets.newServerSocketChannel(fd); } }

    Read the article

  • Viewing the NetBeans Central Registry (Part 2)

    - by Geertjan
    Jens Hofschröer, who has one of the very best NetBeans Platform blogs (if you more or less understand German), and who wrote, sometime ago, the initial version of the Import Statement Organizer, as well as being the main developer of a great gear design & manufacturing tool on the NetBeans Platform in Aachen, commented on my recent blog entry "Viewing the NetBeans Central Registry", where the root Node of the Central Registry is shown in a BeanTreeView, with the words: "I wrapped that Node in a FilterNode to provide the 'position' attribute and the 'file extension'. All Children are wrapped too. Then I used an OutlineView to show these two properties. Great tool to find wrong layer entries." I asked him for the code he describes above and he sent it to me. He discussed it here in his blog, while all the code involved can be read below. The result is as follows, where you can see that the OutlineView shows information that my simple implementation (via a BeanTreeView) kept hidden: And so here is the definition of the Node. class LayerPropertiesNode extends FilterNode { public LayerPropertiesNode(Node node) { super(node, isFolder(node) ? Children.create(new LayerPropertiesFactory(node), true) : Children.LEAF); } private static boolean isFolder(Node node) { return null != node.getLookup().lookup(DataFolder.class); } @Override public String getDisplayName() { return getLookup().lookup(FileObject.class).getName(); } @Override public Image getIcon(int type) { FileObject fo = getLookup().lookup(FileObject.class); try { DataObject data = DataObject.find(fo); return data.getNodeDelegate().getIcon(type); } catch (DataObjectNotFoundException ex) { Exceptions.printStackTrace(ex); } return super.getIcon(type); } @Override public Image getOpenedIcon(int type) { return getIcon(type); } @Override public PropertySet[] getPropertySets() { Set set = Sheet.createPropertiesSet(); set.put(new PropertySupport.ReadOnly<Integer>( "position", Integer.class, "Position", null) { @Override public Integer getValue() throws IllegalAccessException, InvocationTargetException { FileObject fileEntry = getLookup().lookup(FileObject.class); Integer posValue = (Integer) fileEntry.getAttribute("position"); return posValue != null ? posValue : Integer.valueOf(0); } }); set.put(new PropertySupport.ReadOnly<String>( "ext", String.class, "Extension", null) { @Override public String getValue() throws IllegalAccessException, InvocationTargetException { FileObject fileEntry = getLookup().lookup(FileObject.class); return fileEntry.getExt(); } }); PropertySet[] original = super.getPropertySets(); PropertySet[] withLayer = new PropertySet[original.length + 1]; System.arraycopy(original, 0, withLayer, 0, original.length); withLayer[withLayer.length - 1] = set; return withLayer; } private static class LayerPropertiesFactory extends ChildFactory<FileObject> { private final Node context; public LayerPropertiesFactory(Node context) { this.context = context; } @Override protected boolean createKeys(List<FileObject> list) { FileObject folder = context.getLookup().lookup(FileObject.class); FileObject[] children = folder.getChildren(); List<FileObject> ordered = FileUtil.getOrder(Arrays.asList(children), false); list.addAll(ordered); return true; } @Override protected Node createNodeForKey(FileObject key) { AbstractNode node = new AbstractNode(org.openide.nodes.Children.LEAF, key.isFolder() ? Lookups.fixed(key, DataFolder.findFolder(key)) : Lookups.singleton(key)); return new LayerPropertiesNode(node); } } } Then here is the definition of the Action, which pops up a JPanel, displaying an OutlineView: @ActionID(category = "Tools", id = "de.nigjo.nb.layerview.LayerViewAction") @ActionRegistration(displayName = "#CTL_LayerViewAction") @ActionReferences({ @ActionReference(path = "Menu/Tools", position = 1450, separatorBefore = 1425) }) @Messages("CTL_LayerViewAction=Display XML Layer") public final class LayerViewAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { try { Node node = DataObject.find(FileUtil.getConfigRoot()).getNodeDelegate(); node = new LayerPropertiesNode(node); node = new FilterNode(node) { @Override public Component getCustomizer() { LayerView view = new LayerView(); view.getExplorerManager().setRootContext(this); return view; } @Override public boolean hasCustomizer() { return true; } }; NodeOperation.getDefault().customize(node); } catch (DataObjectNotFoundException ex) { Exceptions.printStackTrace(ex); } } private static class LayerView extends JPanel implements ExplorerManager.Provider { private final ExplorerManager em; public LayerView() { super(new BorderLayout()); em = new ExplorerManager(); OutlineView view = new OutlineView("entry"); view.addPropertyColumn("position", "Position"); view.addPropertyColumn("ext", "Extension"); add(view); } @Override public ExplorerManager getExplorerManager() { return em; } } }

    Read the article

  • Exception when access inner class reflectively

    - by MikeJiang
    Hi Folk, Here is a sample java program. I wonder why the two approaches reslut different stories. Is it a bug or kind of bitter java feature? And I run the sample upon java 1.5 package test; public class TestOut{ public static void main(String[] args){ new TestIn();//it works Class.forName("test.TestOut$TestIn").newInstance();// throw IllegalAccessException } private static class TestIn{} }

    Read the article

  • How to get Rid of this strange Border on JButton in Windows System look and Feel?

    - by Timo J.
    I have a small Problem with the Layout of my Frame. As You could see in a picture (if i would have my 10 rep ;) ) there is a small Border around my JButtons. I'm already searching long time on this topic and i finally decided to ask for help, i'm just out of ideas. Is this Part of the Windows Theme which shouldn't be changed? It just doesnt fit into my current Layout, as I'm Listing TextBoxes and Comboboxes on Page Axis without any Border. I would be very happy if there is solution for this issue. Thanks in advance! EDIT 1: I do not mean the Focus Border. I like the Highlighting of a focussed Element. What i mean is the Border in the Background Color which causes a small distance of background-colored space beetween a JButton and another Element. (Picture on Personnal Webspace: http://tijamocobs.no-ip.biz/border_jbutton.png) EDIT 2: I'm using the Windows 8 Look and Feel but saw this Problem on Windows 7 Look and Feel, too. short Example import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class TestFrame extends JFrame { public TestFrame(){ setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS)); for (int i = 0; i < 3; i++) { JButton btn = new JButton("."); // not working: // btn.setBorder(null); // btn.setBorder(BorderFactory.createEmptyBorder()); add(btn); } pack(); } public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); TestFrame tiss = new TestFrame(); tiss.setVisible(true); } } Example Code (long version): import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class TestFrame extends JFrame { public TestFrame(){ JPanel muh = new JPanel(); muh.setLayout(new BoxLayout(muh, BoxLayout.PAGE_AXIS)); for (int i = 0; i < 3; i++) { Container c = new JPanel(); c.setLayout(new BoxLayout(c, BoxLayout.LINE_AXIS)); Box bx = Box.createHorizontalBox(); final String[] tmp = {"anything1","anything2"}; JComboBox<String> cmbbx = new JComboBox<String>(tmp); cmbbx.setMinimumSize(new Dimension(80,20)); bx.add(cmbbx); JButton btn = new JButton("."); btn.setMinimumSize(new Dimension(cmbbx.getMinimumSize().height,cmbbx.getMinimumSize().height)); btn.setPreferredSize(new Dimension(30,30)); btn.setMaximumSize(new Dimension(30,30)); bx.add(btn); c.setMaximumSize(new Dimension(Integer.MAX_VALUE,30)); c.add(new JLabel("Just anything")); c.add(bx); muh.add(c); } add(muh,BorderLayout.CENTER); pack(); } public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); TestFrame tiss = new TestFrame(); tiss.setVisible(true); } }

    Read the article

  • Java: how to avoid circual references when dumping object information with reflection?

    - by Tom
    I've modified an object dumping method to avoid circual references causing a StackOverflow error. This is what I ended up with: //returns all fields of the given object in a string public static String dumpFields(Object o, int callCount, ArrayList excludeList) { //add this object to the exclude list to avoid circual references in the future if (excludeList == null) excludeList = new ArrayList(); excludeList.add(o); callCount++; StringBuffer tabs = new StringBuffer(); for (int k = 0; k < callCount; k++) { tabs.append("\t"); } StringBuffer buffer = new StringBuffer(); Class oClass = o.getClass(); if (oClass.isArray()) { buffer.append("\n"); buffer.append(tabs.toString()); buffer.append("["); for (int i = 0; i < Array.getLength(o); i++) { if (i < 0) buffer.append(","); Object value = Array.get(o, i); if (value != null) { if (excludeList.contains(value)) { buffer.append("circular reference"); } else if (value.getClass().isPrimitive() || value.getClass() == java.lang.Long.class || value.getClass() == java.lang.String.class || value.getClass() == java.lang.Integer.class || value.getClass() == java.lang.Boolean.class) { buffer.append(value); } else { buffer.append(dumpFields(value, callCount, excludeList)); } } } buffer.append(tabs.toString()); buffer.append("]\n"); } else { buffer.append("\n"); buffer.append(tabs.toString()); buffer.append("{\n"); while (oClass != null) { Field[] fields = oClass.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i] == null) continue; buffer.append(tabs.toString()); fields[i].setAccessible(true); buffer.append(fields[i].getName()); buffer.append("="); try { Object value = fields[i].get(o); if (value != null) { if (excludeList.contains(value)) { buffer.append("circular reference"); } else if ((value.getClass().isPrimitive()) || (value.getClass() == java.lang.Long.class) || (value.getClass() == java.lang.String.class) || (value.getClass() == java.lang.Integer.class) || (value.getClass() == java.lang.Boolean.class)) { buffer.append(value); } else { buffer.append(dumpFields(value, callCount, excludeList)); } } } catch (IllegalAccessException e) { System.out.println("IllegalAccessException: " + e.getMessage()); } buffer.append("\n"); } oClass = oClass.getSuperclass(); } buffer.append(tabs.toString()); buffer.append("}\n"); } return buffer.toString(); } The method is initially called like this: System.out.println(dumpFields(obj, 0, null); So, basically I added an excludeList which contains all the previousely checked objects. Now, if an object contains another object and that object links back to the original object, it should not follow that object further down the chain. However, my logic seems to have a flaw as I still get stuck in an infinite loop. Does anyone know why this is happening?

    Read the article

  • UndoRedo on Nodes

    - by Geertjan
    When a change is made to the property in the Properties Window, below, the undo/redo functionality becomes enabled: When undo/redo are invoked, e.g., via the buttons in the toolbar, the display name of the node changes accordingly. The only problem I have is that the buttons only become enabled when the Person Window is selected, not when the Properties Window is selected, which would be desirable. Here's the Person object: public class Person implements PropertyChangeListener {     private String name;     public static final String PROP_NAME = "name";     public Person(String name) {         this.name = name;     }     public String getName() {         return name;     }     public void setName(String name) {         String oldName = this.name;         this.name = name;         propertyChangeSupport.firePropertyChange(PROP_NAME, oldName, name);     }     private transient final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);     public void addPropertyChangeListener(PropertyChangeListener listener) {         propertyChangeSupport.addPropertyChangeListener(listener);     }     public void removePropertyChangeListener(PropertyChangeListener listener) {         propertyChangeSupport.removePropertyChangeListener(listener);     }     @Override     public void propertyChange(PropertyChangeEvent evt) {         propertyChangeSupport.firePropertyChange(evt);     } } And here's the Node with UndoRedo enablement: public class PersonNode extends AbstractNode implements UndoRedo.Provider, PropertyChangeListener {     private UndoRedo.Manager manager = new UndoRedo.Manager();     private boolean undoRedoEvent;     public PersonNode(Person person) {         super(Children.LEAF, Lookups.singleton(person));         person.addPropertyChangeListener(this);         setDisplayName(person.getName());     }     @Override     protected Sheet createSheet() {         Sheet sheet = Sheet.createDefault();         Sheet.Set set = Sheet.createPropertiesSet();         set.put(new NameProperty(getLookup().lookup(Person.class)));         sheet.put(set);         return sheet;     }     @Override     public void propertyChange(PropertyChangeEvent evt) {         if (evt.getPropertyName().equals(Person.PROP_NAME)) {             firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue());         }     }     public void fireUndoableEvent(String property, Person source, Object oldValue, Object newValue) {         manager.addEdit(new MyAbstractUndoableEdit(source, oldValue, newValue));     }     @Override     public UndoRedo getUndoRedo() {         return manager;     }     @Override     public String getDisplayName() {         Person p = getLookup().lookup(Person.class);         if (p != null) {             return p.getName();         }         return super.getDisplayName();     }     private class NameProperty extends PropertySupport.ReadWrite<String> {         private Person p;         public NameProperty(Person p) {             super("name", String.class, "Name", "Name of Person");             this.p = p;         }         @Override         public String getValue() throws IllegalAccessException, InvocationTargetException {             return p.getName();         }         @Override         public void setValue(String newValue) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {             String oldValue = p.getName();             p.setName(newValue);             if (!undoRedoEvent) {                 fireUndoableEvent("name", p, oldValue, newValue);                 fireDisplayNameChange(oldValue, newValue);             }         }     }     class MyAbstractUndoableEdit extends AbstractUndoableEdit {         private final String oldValue;         private final String newValue;         private final Person source;         private MyAbstractUndoableEdit(Person source, Object oldValue, Object newValue) {             this.oldValue = oldValue.toString();             this.newValue = newValue.toString();             this.source = source;         }         @Override         public boolean canRedo() {             return true;         }         @Override         public boolean canUndo() {             return true;         }         @Override         public void undo() throws CannotUndoException {             undoRedoEvent = true;             source.setName(oldValue.toString());             fireDisplayNameChange(oldValue, newValue);             undoRedoEvent = false;         }         @Override         public void redo() throws CannotUndoException {             undoRedoEvent = true;             source.setName(newValue.toString());             fireDisplayNameChange(oldValue, newValue);             undoRedoEvent = false;         }     } } Does anyone out there know how to have the Undo/Redo functionality enabled when the Properties Window is selected?

    Read the article

  • Using reflection to change static final File.separatorChar for unit testing?

    - by Stefan Kendall
    Specifically, I'm trying to create a unit test for a method which requires uses File.separatorChar to build paths on windows and unix. The code must run on both platforms, and yet I get errors with JUnit when I attempt to change this static final field. Anyone have any idea what's going on? Field field = java.io.File.class.getDeclaredField( "separatorChar" ); field.setAccessible(true); field.setChar(java.io.File.class,'/'); When I do this, I get IllegalAccessException: Can not set static final char field java.io.File.separatorChar to java.lang.Character Thoughts?

    Read the article

  • Android serialization: ImageView

    - by embo
    I have a simple class: public class Ball2 extends ImageView implements Serializable { public Ball2(Context context) { super(context); } } Serialization ok: private void saveState() throws IOException { ObjectOutputStream oos = new ObjectOutputStream(openFileOutput("data", MODE_PRIVATE)); try { Ball2 data = new Ball2(Game2.this); oos.writeObject(data); oos.flush(); } catch (Exception e) { Log.e("write error", e.getMessage(), e); } finally { oos.close(); } } But deserealization private void loadState() throws IOException { ObjectInputStream ois = new ObjectInputStream(openFileInput("data")); try { Ball2 data = (Ball2) ois.readObject(); } catch (Exception e) { Log.e("read error", e.getMessage(), e); } finally { ois.close(); } } fail with error: 03-24 21:52:43.305: ERROR/read error(1948): java.io.InvalidClassException: android.widget.ImageView; IllegalAccessException How deserialize object correctly?

    Read the article

  • Impossible to do POSTs with appengine-jruby/RoR: Reflection is not allowed

    - by Joel Cuevas
    I'm trying to build a site with RoR on Google App Engine. I'm using the google-appengine gem (http://appengine-jruby.googlecode.com) and following the instructions in (http://gist.github.com/268192). The problem is that I can't submit ANY form! I've already tried this in two diferent clean Win 7 Pro envs and the result is the same. After install Ruby 1.8.6 (One-Click Installer): 1. gem update --system 2. gem install rails 3. gem install google-appengine 4. gem install rails_dm_datastore 5. gem install activerecord-nulldb-adapter 6. curl -O http://appengine-jruby.googlecode.com/hg/demos/rails2/rails2_appengine.rb 7. ruby rails2_appengine.rb (previously downloaded) 8. rails myproj 9. chmod myproj 10. ruby script/generate dd_model MyModel f1:string f2:float f3:float f4:float f5:integer f6:integer f7:integer -f 11. ruby script/generate scaffold MyModel f1:string f2:float f3:float f4:float f5:integer f6:integer f7:integer -f --skip-migration 12. dev_appserver.rb -p 3000 . At this point, I manually test the scaffold in (http://localhost:3000/my_models). The index is OK, then I create a new registry with the generated form, everything's fine, but when I try to create a second one, I get a "java.lang.RuntimeException: DummyDynamicScope should never be used for backref storage" in the console. As far as I read this is a won't-fix behavior in JRuby 1.4.1, but it's converted to a debug only warning in 1.5.0, so I proceed to install the pre release. 13. gem install appengine-jruby-jars --pre With this, that exception is solved and everything works great... until I move the project to the GAE server. 14. ruby appcfg.rb update . And now, in (http://myproj.appspot.com/my_models), again, the index is fine, also the new form, but in the moment that I submit it with valid data, I get a 500 error: "java.lang.IllegalAccessException: Reflection is not allowed on public int". As I said, this behavior is not present in the local SDK. In both cases, I'm completely unable to post anything. This is what I have right now in the GAE environment: Ruby version 1.8.7 (java) RubyGems disabled Rack version 1.1 Rails version 2.3.5 Action Pack version 2.3.5 Active Support version 2.3.5 DataMapper version 0.10.2 Environment production JRuby Runtime version 1.5.0.pre JRuby-Rack version 0.9.7 AppEngine SDK version Google App Engine/1.3.3 AppEngine APIs version 0.0.15 And this are my intalled gems: actionmailer (2.3.5) actionpack (2.3.5) activerecord (2.3.5) activerecord-nulldb-adapter (0.2.0) activeresource (2.3.5) activesupport (2.3.5) addressable (2.1.2) appengine-apis (0.0.15) appengine-jruby-jars (0.0.8.pre, 0.0.7) appengine-rack (0.0.8) appengine-sdk (1.3.3.1) appengine-tools (0.0.12) bundler08 (0.8.5) dm-appengine (0.0.8) dm-ar-finders (0.10.2) dm-core (0.10.2) dm-timestamps (0.10.2) dm-validations (0.10.2) extlib (0.9.14) fxri (0.3.7, 0.3.6) google-appengine (0.0.12) hpricot (0.8.2 x86-mswin32, 0.6 mswin32) jruby-rack (0.9.8, 0.9.7) log4r (1.1.7, 1.0.5) rack (1.1.0, 1.0.1) rails (2.3.5) rails_appengine (0.0.3) rails_dm_datastore (0.2.9) rake (0.8.7, 0.7.3) rubygems-update (1.3.7, 1.3.6) rubyzip (0.9.4) sources (0.0.1) win32-api (1.4.6 x86-mswin32-60, 1.0.4 mswin32) win32-clipboard (0.5.2, 0.4.3) win32-dir (0.3.6, 0.3.2) win32-eventlog (0.5.2, 0.4.6) win32-file (0.6.3, 0.5.4) win32-file-stat (1.3.4, 1.2.7) win32-process (0.6.2, 0.5.3) win32-sapi (0.1.5, 0.1.4) win32-sound (0.4.2, 0.4.1) windows-api (0.4.0, 0.2.0) windows-pr (1.0.9, 0.7.2) I'm unable to attach the full logs of the exceptions because of the character limits, but I can provide them under request. Here's an abstract of them: DummyDynamicScope (dev and prod envs): 14-may-2010 7:18:40 com.google.appengine.tools.development.ApiProxyLocalImpl log SEVERE: [1273821520195000] javax.servlet.ServletContext log: Application Error java.lang.RuntimeException: DummyDynamicScope should never be used for backref storage at org.jruby.runtime.scope.DummyDynamicScope.getBackRef(DummyDynamicScope.java:49) at org.jruby.RubyRegexp.updateBackRef(RubyRegexp.java:1404) at org.jruby.RubyRegexp.updateBackRef(RubyRegexp.java:1396) at org.jruby.RubyRegexp.search(RubyRegexp.java:1386) at org.jruby.RubyRegexp.op_match(RubyRegexp.java:1301) at org.jruby.RubyString.op_match(RubyString.java:1446) at org.jruby.RubyString$i_method_1_0$RUBYINVOKER$op_match.call(org/jruby/RubyString$i_method_1_0$RUBYINVOKER$op_match.gen) at org.jruby.internal.runtime.methods.JavaMethod$JavaMethodOneOrN.call(JavaMethod.java:721) at org.jruby.RubyClass.finvoke(RubyClass.java:472) at org.jruby.RubyObject.send(RubyObject.java:1442) at org.jruby.RubyObject$i_method_multi$RUBYINVOKER$send.call(org/jruby/RubyObject$i_method_multi$RUBYINVOKER$send.gen) at org.jruby.internal.runtime.methods.JavaMethod$JavaMethodZeroOrOneOrTwoOrNBlock.call(JavaMethod.java:276) at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:330) at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:189) at ruby.jit.ruby.C_3a_.Desarrollo.AppEngine.gorgory.WEB_minus_INF.lib.gems_dot_jar.bundler_gems.jruby.$1_dot_8.gems.dm_minus_validations_minus_0_dot_10_dot_2.lib.dm_minus_validations.validators.numeric_validator.validate_with_comparison at ruby.jit.ruby.C_3a_.Desarrollo.AppEngine.gorgory.WEB_minus_INF.lib.gems_dot_jar.bundler_gems.jruby.$1_dot_8.gems.dm_minus_validations_minus_0_dot_10_dot_2.lib.dm_minus_validations.validators.numeric_validator.validate_with_comparison at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:102) at org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:144) at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:280) at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:69) at org.jruby.ast.FCallManyArgsNode.interpret(FCallManyArgsNode.java:60) at org.jruby.ast.NewlineNode.interpret(NewlineNode.java:104) at org.jruby.internal.runtime.methods.InterpretedMethod.call(InterpretedMethod.java:229) at org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:193) at org.jruby.RubyClass.finvoke(RubyClass.java:491) at org.jruby.RubyObject.send(RubyObject.java:1448) at org.jruby.RubyObject$i_method_multi$RUBYINVOKER$send.call(org/jruby/RubyObject$i_method_multi$RUBYINVOKER$send.gen) at org.jruby.internal.runtime.methods.JavaMethod$JavaMethodZeroOrOneOrTwoOrThreeOrNBlock.call(JavaMethod.java:293) at org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:350) at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:229) at ruby.jit.ruby.C_3a_.Desarrollo.AppEngine.gorgory.WEB_minus_INF.lib.gems_dot_jar.bundler_gems.jruby.$1_dot_8.gems.dm_minus_validations_minus_0_dot_10_dot_2.lib.dm_minus_validations.validators.numeric_validator.validate_with28985350_50 at ruby.jit.ruby.C_3a_.Desarrollo.AppEngine.gorgory.WEB_minus_INF.lib.gems_dot_jar.bundler_gems.jruby.$1_dot_8.gems.dm_minus_validations_minus_0_dot_10_dot_2.lib.dm_minus_validations.validators.numeric_validator.validate_with28985350_50 at org.jruby.internal.runtime.methods.JittedMethod.call(JittedMethod.java:221) at org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:201) at org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:227) at org.jruby.ast.FCallThreeArgNode.interpret(FCallThreeArgNode.java:40) Reflection (only prod env): Java::JavaLang::SecurityException (java.lang.IllegalAccessException: Reflection is not allowed on public int java.lang.String$CaseInsensitiveComparator.compare(java.lang.String,java.lang.String)): com.google.appengine.runtime.Request.process-92563a0605f433ea(Request.java) java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject.java:40) org.jruby.javasupport.JavaMethod.<init>(JavaMethod.java:176) org.jruby.javasupport.JavaMethod.create(JavaMethod.java:183) org.jruby.java.invokers.MethodInvoker.createCallable(MethodInvoker.java:23) org.jruby.java.invokers.RubyToJavaInvoker.<init>(RubyToJavaInvoker.java:63) org.jruby.java.invokers.MethodInvoker.<init>(MethodInvoker.java:13) org.jruby.java.invokers.InstanceMethodInvoker.<init>(InstanceMethodInvoker.java:15) org.jruby.javasupport.JavaClass$InstanceMethodInvokerInstaller.install(JavaClass.java:339) org.jruby.javasupport.JavaClass.installClassMethods(JavaClass.java:723) org.jruby.javasupport.JavaClass.setupProxy(JavaClass.java:586) org.jruby.javasupport.Java.createProxyClass(Java.java:506) org.jruby.javasupport.Java.getProxyClass(Java.java:445) org.jruby.javasupport.Java.getInstance(Java.java:354) org.jruby.javasupport.JavaUtil.convertJavaToUsableRubyObject(JavaUtil.java:143) org.jruby.javasupport.JavaClass$ConstantField.install(JavaClass.java:360) org.jruby.javasupport.JavaClass.installClassFields(JavaClass.java:711) org.jruby.javasupport.JavaClass.setupProxy(JavaClass.java:585) org.jruby.javasupport.Java.createProxyClass(Java.java:506) org.jruby.javasupport.Java.getProxyClass(Java.java:445) org.jruby.javasupport.Java.getProxyOrPackageUnderPackage(Java.java:885) org.jruby.javasupport.Java.get_proxy_or_package_under_package(Java.java:918) org.jruby.javasupport.JavaUtilities.get_proxy_or_package_under_package(JavaUtilities.java:54) org.jruby.javasupport.JavaUtilities$s_method_2_0$RUBYINVOKER$get_proxy_or_package_under_package.call(org/jruby/javasupport/JavaUtilities$s_method_2_0$RUBYINVOKER$get_proxy_or_package_under_package.gen:65535) org.jruby.runtime.callsite.CachingCallSite.cacheAndCall(CachingCallSite.java:329) org.jruby.runtime.callsite.CachingCallSite.call(CachingCallSite.java:188) org.jruby.ast.CallTwoArgNode.interpret(CallTwoArgNode.java:59) org.jruby.ast.NewlineNode.interpret(NewlineNode.java:104) org.jruby.ast.BlockNode.interpret(BlockNode.java:71) org.jruby.internal.runtime.methods.InterpretedMethod.call(InterpretedMethod.java:113) org.jruby.internal.runtime.methods.DefaultMethod.call(DefaultMethod.java:138) org.jruby.javasupport.util.RuntimeHelpers$MethodMissingMethod.call(RuntimeHelpers.java:389) org.jruby.internal.runtime.methods.DynamicMethod.call(DynamicMethod.java:182) What should I do now? Any hint would be wellcome. Thanks!

    Read the article

  • JDK7?????

    - by Todd Bao
    ??JSR 334,JDK 7?????????????,???:1. switch????String????:    public static void switchString(String s){        switch (s){        case "db": ...        case "wls": ...        case "idm": ...        case "soa": ...        case "fa": ...        default: ...        }    }2. ?????????? - "0b"???"_"???,?????????? a. ???????????, 0b: ????????????:        byte b1 = 0b00100001;     // New        byte b2 = 0x21;        // Old        byte b3 = 33;        // Old b. ??????????????,?????,????????????:    long phone_nbr = 021_1111_2222;3. ???????????? - "?? new",????????:        ArrayList<String> al1 = new ArrayList<String>();    // Old        ArrayList<String> al2 = new ArrayList<>();        // New4. ????reflect?????????? - ReflectOperationException,????:    ClassNotFoundException,     IllegalAccessException,     InstantiationException,     InvocationTargetException,     NoSuchFieldException,     NoSuchMethodException5. catch????????,?????????,????????:    try{        // code    }    catch (SQLException | IOException ex) {        // ...    }6. ?????? - ??????????,??????????style:    public void test() throws NoSuchMethodException, NoSuchFieldException{    // ??        try{            // code        }        catch (RelectiveOperationException ex){    // ??            throws ex;        }    }7. ???try()?? - Try with Resources,?????????????(???????????java.lang.AutoCloseable??),???????try?????"("??"{":    try(BufferedReader br = new BufferedReader(new FileReader("/home/oracle/temp.txt"))){        ... br.readLine() ...    }try-with-resources?????catch,??????????catch???????Todd

    Read the article

  • How do I avoid repetition in Java ResourceBundle strings?

    - by Trejkaz
    We had a lot of strings which contained the same sub-string, from sentences about checking the log or how to contact support, to branding-like strings containing the company or product name. The repetition was causing a few issues for ourselves (primarily typos or copy/paste errors) but it also causes issues in that it increases the amount of text our translator has to translate. The solution I came up with went something like this: public class ExpandingResourceBundleControl extends ResourceBundle.Control { public static final ResourceBundle.Control EXPANDING = new ExpandingResourceBundleControl(); private ExpandingResourceBundleControl() { } @Override public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException { ResourceBundle inner = super.newBundle(baseName, locale, format, loader, reload); return inner == null ? null : new ExpandingResourceBundle(inner, loader); } } ExpandingResourceBundle delegates to the real resource bundle but performs conversion of {{this.kind.of.thing}} to look up the key in the resources. Every time you want to get one of these, you have to go: ResourceBundle.getBundle("com/acme/app/Bundle", EXPANDING); And this works fine -- for a while. What eventually happens is that some new code (in our case autogenerated code which was spat out of Matisse) looks up the same resource bundle without specifying the custom control. This appears to be non-reproducible if you write a simple unit test which calls it with and then without, but it occurs when the application is run for real. Somehow the cache inside ResourceBundle ejects the good value and replaces it with the broken one. I am yet to figure out why and Sun's jar files were compiled without debug info so debugging it is a chore. My questions: Is there some way of globally setting the default ResourceBundle.Control that I might not be aware of? That would solve everything rather elegantly. Is there some other way of handling this kind of thing elegantly, perhaps without tampering with the ResourceBundle classes at all?

    Read the article

  • Why am I having this InstantiationException in Java when accessing final local variables?

    - by Oscar Reyes
    I was playing with some code to make a "closure like" construct ( not working btw ) Everything looked fine but when I tried to access a final local variable in the code, the exception InstantiationException is thrown. If I remove the access to the local variable either by removing it altogether or by making it class attribute instead, no exception happens. The doc says: InstantiationException Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated. The instantiation can fail for a variety of reasons including but not limited to: - the class object represents an abstract class, an interface, an array class, a primitive type, or void - the class has no nullary constructor What other reason could have caused this problem? Here's the code. comment/uncomment the class attribute / local variable to see the effect (lines:5 and 10 ). import javax.swing.*; import java.awt.event.*; import java.awt.*; class InstantiationExceptionDemo { //static JTextField field = new JTextField();// works if uncommented public static void main( String [] args ) { JFrame frame = new JFrame(); JButton button = new JButton("Click"); final JTextField field = new JTextField();// fails if uncommented button.addActionListener( new _(){{ System.out.println("click " + field.getText()); }}); frame.add( field ); frame.add( button, BorderLayout.SOUTH ); frame.pack();frame.setVisible( true ); } } class _ implements ActionListener { public void actionPerformed( ActionEvent e ){ try { this.getClass().newInstance(); } catch( InstantiationException ie ){ throw new RuntimeException( ie ); } catch( IllegalAccessException ie ){ throw new RuntimeException( ie ); } } } Is this a bug in Java? edit Oh, I forgot, the stacktrace ( when thrown ) is: Caused by: java.lang.InstantiationException: InstantiationExceptionDemo$1 at java.lang.Class.newInstance0(Class.java:340) at java.lang.Class.newInstance(Class.java:308) at _.actionPerformed(InstantiationExceptionDemo.java:25)

    Read the article

  • hadoop implementing a generic list writable

    - by Guruprasad Venkatesh
    I am working on building a map reduce pipeline of jobs(with one MR job's output feeding to another as input). The values being passed around are fairly complex, in that there are lists of different types and hash maps with values as lists. Hadoop api does not seem to have a ListWritable. Am trying to write a generic one, but it seems i can't instantiate a generic type in my readFields implementation, unless i pass in the class type itself: public class ListWritable<T extends Writable> implements Writable { private List<T> list; private Class<T> clazz; public ListWritable(Class<T> clazz) { this.clazz = clazz; list = new ArrayList<T>(); } @Override public void write(DataOutput out) throws IOException { out.writeInt(list.size()); for (T element : list) { element.write(out); } } @Override public void readFields(DataInput in) throws IOException{ int count = in.readInt(); this.list = new ArrayList<T>(); for (int i = 0; i < count; i++) { try { T obj = clazz.newInstance(); obj.readFields(in); list.add(obj); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } But hadoop requires all writables to have a no argument constructor to read the values back. Has anybody tried to do the same and solved this problem? TIA.

    Read the article

  • Most Elegant Way to write isPrime in java

    - by Anantha Kumaran
    public class Prime { public static boolean isPrime1(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } for (int i = 2; i <= Math.sqrt(n) + 1; i++) { if (n % i == 0) { return false; } } return true; } public static boolean isPrime2(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } if (n % 2 == 0) { return false; } for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) { if (n % i == 0) { return false; } } return true; } } public class PrimeTest { public PrimeTest() { } @Test public void testIsPrime() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { Prime prime = new Prime(); TreeMap<Long, String> methodMap = new TreeMap<Long, String>(); for (Method method : Prime.class.getDeclaredMethods()) { long startTime = System.currentTimeMillis(); int primeCount = 0; for (int i = 0; i < 1000000; i++) { if ((Boolean) method.invoke(prime, i)) { primeCount++; } } long endTime = System.currentTimeMillis(); Assert.assertEquals(method.getName() + " failed ", 78498, primeCount); methodMap.put(endTime - startTime, method.getName()); } for (Entry<Long, String> entry : methodMap.entrySet()) { System.out.println(entry.getValue() + " " + entry.getKey() + " Milli seconds "); } } } I am trying to find the fastest way to check whether the given number is prime or not. This is what is finally came up with. Is there any better way than the second implementation(isPrime2).

    Read the article

  • No operations allowed after statement closed issue

    - by Washu
    I have the next methods in my singleton to execute the JDBC connections public void openDB() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException { Class.forName("com.mysql.jdbc.Driver").newInstance(); String url = "jdbc:mysql://localhost/mbpe_peru";//mydb conn = DriverManager.getConnection(url, "root", "admin"); st = conn.createStatement(); } public void sendQuery(String query) throws SQLException { st.executeUpdate(query); } public void closeDB() throws SQLException { st.close(); conn.close(); } And I'm having a problem in a void where i have to call this twice. private void jButton1ActionPerformed(ActionEvent evt) { Main.getInstance().openDB(); Main.getInstance().sendQuery("call insertEntry('"+EntryID()+"','"+SupplierID()+"');"); Main.getInstance().closeDB(); Main.getInstance().openDB(); for(int i=0;i<dataBox.length;i++){ Main.getInstance().sendQuery("call insertCount('"+EntryID()+"','"+SupplierID()+"','"+BoxID()+"'); Main.getInstance().closeDB(); } } I have already tried to keep the connection open and send the 2 querys and after that closed and it didnt work... The only way it worked was to not use the methods, declare the commands for the connection and use different variables for the connection and the statement. I thought that if i close the Connecion and the Statement I could use the variable once again since is a method but I'm not able to. Is there any way to solve this using my methods for the JDBC connection?

    Read the article

  • Java program will read from database, but not write to it

    - by ck1221
    I have a Java program that successfully connects to a mysql database that is hosted on godaddy's server. I can read from that db with out issue, however, when I try to write to it with INSERT or UPDATE for example, the query does not execute. I am using the 'admin' account that I set up through godaddy, I realize this is not the root account. I have checked and verified that the connection is not read only, and have logged out of phpmyadmin while the query ran. I'm not sure what else I can try or if anyone has experienced this issue. Maybe a setting to the connection I have failed to set? Or maybe its not possible since the db is hosted on godaddy's servers? Any help is great! Thanks. Here is some relevant code: Connection to db: Connection con; public DBconnection(String url, String user, String pass) { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection (url,user,pass); if(!con.isClosed()) System.out.println("connecton open"); } catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} } Send Query: public ResultSet executeQuery(String query) { ResultSet rs = null; try { Statement stmt = (Statement) con.createStatement(); rs = stmt.executeQuery(query); //while(rs.next()) //System.out.println(rs.getString("ticket_num")); } catch (SQLException e) {} return rs; } Insert Query (works in phpmyadmin): conn.executeQuery("INSERT INTO tickets VALUES(55555,'12/01/2012','me','reports','test','','','0','Nope')");

    Read the article

  • Problem with Java FX Look and Feel

    - by drachenfels
    Hi, I was looking at some of the examples from the Deitel and Deitel's book for Programming in Java, and one of the first examples is a very simple Swing display. Hence this snippet of code : import javax.swing.*; public class cdea { public static void main(String args[]){ JOptionPane.showMessageDialog(null,"\"Welcome to Java Programming!\""); System.exit(0); //end method main } } I read some stuff regarding how one can get native UI look and feel by using UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); to the program. However, when I just add this to my main method, it gives me a host of errors. Specifically : Multiple markers at this line - Unhandled exception type IllegalAccessException - Unhandled exception type InstantiationException - Unhandled exception type ClassNotFoundException - Unhandled exception type UnsupportedLookAndFeelException However when I use it as part of a try/catch exception loop (is that what it is called?) as detailed on http://stackoverflow.com/questions/1590863/getting-java-applications-to-look-native-on-windows-how , I get the program running properly. Could anyone tell me in simple language why this is so? As in, why can't I directly get the System look and feel; why do I have to use it with exception handling? I'm new to Java, and OOP in general, so I'm sorry if I'm being too simplistic.

    Read the article

  • Reflection to access advanced telephony features

    - by Tyler
    I am trying to use reflection to access some advanced features of the telephony api not published. Currently I am having trouble instantiating a serviceManager object that is needed to get the "phone" service as a binder which I can then use to instantiate a telephony object which is needed to make a call, end call, etc... currently when I make the call serviceManagerObject = tempInterfaceMethod.invoke(null, new Object[] { new Binder() }); it returns a nullPointerException. I believe this has to due with creating a new Binder instead of sending the appropriate binder (which I am unsure of which one is appropriate) public void placeReflectedCall() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InstantiationException { String serviceManagerName = "android.os.IServiceManager"; String serviceManagerNativeName = "android.os.ServiceManagerNative"; String telephonyName = "com.android.internal.telephony.ITelephony"; Class telephonyClass; Class telephonyStubClass; Class serviceManagerClass; Class serviceManagerStubClass; Class serviceManagerNativeClass; Class serviceManagerNativeStubClass; Method telephonyCall; Method telephonyEndCall; Method telephonyAnswerCall; Method getDefault; Method[] temps; Constructor[] serviceManagerConstructor; // Method getService; Object telephonyObject; Object serviceManagerObject; String number = "1111111111"; telephonyClass = Class.forName(telephonyName); telephonyStubClass = telephonyClass.getClasses()[0]; serviceManagerClass = Class.forName(serviceManagerName); serviceManagerNativeClass = Class.forName(serviceManagerNativeName); Method getService = // getDefaults[29]; serviceManagerClass.getMethod("getService", String.class); Method tempInterfaceMethod = serviceManagerNativeClass.getMethod( "asInterface", IBinder.class); // this does not work serviceManagerObject = tempInterfaceMethod.invoke(null, new Object[] { new Binder() }); IBinder retbinder = (IBinder) getService.invoke(serviceManagerObject, "phone"); Method serviceMethod = telephonyStubClass.getMethod("asInterface", IBinder.class); telephonyObject = serviceMethod .invoke(null, new Object[] { retbinder }); telephonyCall = telephonyClass.getMethod("call", String.class); telephonyEndCall = telephonyClass.getMethod("endCall"); telephonyAnswerCall = telephonyClass.getMethod("answerRingingCall"); telephonyCall.invoke(telephonyObject, number); } Thanks in advance for any answers.

    Read the article

  • access exception when invoking method of an anonymous class using java reflection

    - by Asaf David
    Hello I'm trying to use an event dispatcher to allow a model to notify subscribed listeners when it changes. the event dispatcher receives a handler class and a method name to call during dispatch. the presenter subscribes to the model changes and provide a Handler implementation to be called on changes. Here's the code (I'm sorry it's a bit long). EventDispacther: package utils; public class EventDispatcher<T> { List<T> listeners; private String methodName; public EventDispatcher(String methodName) { listeners = new ArrayList<T>(); this.methodName = methodName; } public void add(T listener) { listeners.add(listener); } public void dispatch() { for (T listener : listeners) { try { Method method = listener.getClass().getMethod(methodName); method.invoke(listener); } catch (Exception e) { System.out.println(e.getMessage()); } } } } Model: package model; public class Model { private EventDispatcher<ModelChangedHandler> dispatcher; public Model() { dispatcher = new EventDispatcher<ModelChangedHandler>("modelChanged"); } public void whenModelChange(ModelChangedHandler handler) { dispatcher.add(handler); } public void change() { dispatcher.dispatch(); } } ModelChangedHandler: package model; public interface ModelChangedHandler { void modelChanged(); } Presenter: package presenter; public class Presenter { private final Model model; public Presenter(Model model) { this.model = model; this.model.whenModelChange(new ModelChangedHandler() { @Override public void modelChanged() { System.out.println("model changed"); } }); } } Main: package main; public class Main { public static void main(String[] args) { Model model = new Model(); Presenter presenter = new Presenter(model); model.change(); } } Now, I except to get the "model changed" message. However, I'm getting an java.lang.IllegalAccessException: Class utils.EventDispatcher can not access a member of class presenter.Presenter$1 with modifiers "public". I understand that the class to blame is the anonymous class i created inside the presenter, however I don't know how to make it any more 'public' than it currently is. If i replace it with a named nested class it seem to work. It also works if the Presenter and the EventDispatcher are in the same package, but I can't allow that (several presenters in different packages should use the EventDispatcher) any ideas?

    Read the article

1 2  | Next Page >