访问方法时出现IllegalAccess错误

时间:2017-06-02 16:36:55

标签: java exception inheritance access-modifiers

我有两节课。

  1. A类,它扩展了B类
  2. B类有内部静态最终类,比方说C
  3. 此内部静态类C具有私有方法method1。
  4. D类扩展了A类并调用了内部类C的方法并注入了它自己。
  5. 更详细:

    var socialNetworkUsed = ""
    var twitterIDToken = ""
    var facebookIDToken = ""
    var googleIDToken = ""
    var twitterHasSegued = false //used to stop twitter interupting the segue into the app after login has happened
    
    @IBAction func loginWIthEmailButton(_ sender: Any) {
        print("login With Email Pressed")
        performSegue(withIdentifier: "emailLogin", sender: self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loginWithTwitter()
        loginWithFacebook()
        loginWithGoogle()
        //getCognitoID()
    
        GIDSignIn.sharedInstance().clientID = "#################"
    
        GIDSignIn.sharedInstance().uiDelegate = self
        GIDSignIn.sharedInstance().delegate = self
        GIDSignIn.sharedInstance().shouldFetchBasicProfile = true
    
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func loginWithTwitter () {
    
        let logInButton = TWTRLogInButton { (session, error) in
            if let unwrappedSession = session {
    
                self.socialNetworkUsed = "Twitter"
                self.twitterIDToken = unwrappedSession.authToken + ";" + unwrappedSession.authTokenSecret
    
    
                let client = TWTRAPIClient.withCurrentUser()
    
                client.requestEmail { email, error in
                    if (email != nil) {
                        print("signed in as \(String(describing: session?.userName))")
                        print(email!)
    
    
                    } else {
                        print("error: \(String(describing: error?.localizedDescription))")
                    }
                }
    
                self.signInToCognito(theUser: unwrappedSession)
                self.twitterHasSegued = true
    
            } else {
                NSLog("Login error: %@", error!.localizedDescription);
            }
    
        }
    
        if twitterHasSegued == false {
        // TODO: Change where the log in button is positioned in your view
        let button = logInButton
        button.center = self.view.center
        self.view.addSubview(button)
        }
    }
    
    func loginWithFacebook () {
    
        let loginButton = FBSDKLoginButton()
        loginButton.readPermissions = ["public_profile", "email", "user_friends"]
        loginButton.center.y = self.view.center.y/3
        loginButton.center.x = self.view.center.x
    
        self.view.addSubview(loginButton)
        loginButton.delegate = self
    
    }
    
    
    
    public func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
        if result != nil {
        self.socialNetworkUsed = "Facebook"
        if let theUser = result {
            self.facebookIDToken = theUser.token.tokenString
            print("First token \(facebookIDToken)")
            FBSDKGraphRequest(graphPath:"me", parameters: ["fields" : "id, name, email"]).start(completionHandler: { (connection, result, error) in
                if error == nil {
                    self.facebookIDToken = FBSDKAccessToken.current().tokenString
    
                    print("Second token \(self.facebookIDToken)")
    
    
                    let data:[String:AnyObject] = result as! [String : AnyObject]
                    print("Facebook logged in: \(data["name"]!)\(data["email"]!)")
    
                    self.signInToCognito(theUser: data)
    
                } else {
                    print("Error Getting Info \(error!)");
                }
            })
            }}
    }
    
    
    /**
     Sent to the delegate when the button was used to logout.
     - Parameter loginButton: The button that was clicked.
     */
    public func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!){
        print("loggedout of facebook")
    }
    
    func loginWithGoogle () {
        let loginButton = GIDSignInButton()
        loginButton.center.y = view.center.y/1.5
        loginButton.center.x = view.center.x
    
        view.addSubview(loginButton)
    
    
    }
    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if (error == nil) {
            socialNetworkUsed = "Google"
            // Perform any operations on signed in user here.
            let userId = user.userID                  // For client-side use only!
            self.googleIDToken = user.authentication.idToken // Safe to send to the server
            let fullName = user.profile.name
            let givenName = user.profile.givenName
            let familyName = user.profile.familyName
            let email = user.profile.email
            signInToCognito(theUser: user)
            print(userId, fullName, email, givenName, familyName)
    
            // ...
        } else {
            print("\(error.localizedDescription)")
        }
    }
    
    func signInToCognito (theUser: Any) {
    
        let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.EUWest2, identityPoolId:"#######################",identityProviderManager: self)
        let configuration = AWSServiceConfiguration(region:.EUWest2, credentialsProvider:credentialsProvider)
    
        AWSServiceManager.default().defaultServiceConfiguration = configuration
    
    
    
        credentialsProvider.getIdentityId().continueWith { (task: AWSTask!) -> AnyObject! in
    
            if (task.error != nil) {
                print("Error: " + (task.error?.localizedDescription)!)
    
            } else {
                // the task result will contain the identity id
                let cognitoId = task.result
                let syncClient = AWSCognito.default()
                print("sync client is \(syncClient.configuration.userAgent)")
            }
            return nil
        }
    
    
            let syncClient = AWSCognito.default()
            // Create a record in a dataset and synchronize with the server
            let dataset = syncClient.openOrCreateDataset("myDataset")
    
            if self.socialNetworkUsed == "Twitter" { // if they have used twitter to login
                let user = theUser as! TWTRSession
                dataset.setString(user.userName, forKey:"userName")
                dataset.setString("Mystery Climber", forKey: "name")
                let client = TWTRAPIClient.withCurrentUser()
    
                client.requestEmail { email, error in
                    if (email != nil) {
                        dataset.setString(email, forKey: "email")
                        print(email)
                    } else {
                        print("error: \(error?.localizedDescription)")
                        dataset.setString("none@none.com", forKey: "email")
                    }
                }
    
            } else if self.socialNetworkUsed == "Facebook" { // if they have used facebook to login
                let user = theUser as! [String : AnyObject]
                print("sign in to cognotio function facebook section \(user["name"]) & \(user["email"])")
                dataset.setString(user["name"] as! String, forKey: "name")
                if let email = user["email"] as? String {
                    dataset.setString(email, forKey: "email")
                }
    
            } else if self.socialNetworkUsed == "Google" {//if they have used google to login
                let user = theUser as! GIDGoogleUser
                dataset.setString(user.profile.email, forKey: "email")
                dataset.setString(user.profile.name, forKey: "name")
            }
    
            dataset.synchronize().continueWith {(task: AWSTask!) -> AnyObject! in
                if task.error != nil {
                    print("dataset error\(task.error)")
                } else {
                    DispatchQueue.main.sync {
                        self.performSegue(withIdentifier: "toTheHomePage", sender: self)
                    }
                }
                return () as AnyObject
            }
    
    
        print(self.socialNetworkUsed)
    
    }
    
    
    public func logins() -> AWSTask<NSDictionary> {
        if socialNetworkUsed == "Twitter" {
            let result = NSDictionary(dictionary: [AWSIdentityProviderTwitter: twitterIDToken])
            print("Twitter results done")
            return AWSTask(result: result)
        } else if socialNetworkUsed == "Facebook" {
            if let token = FBSDKAccessToken.current() {
                print("Facebook results done")
                return AWSTask(result: [AWSIdentityProviderFacebook: token])
            } else {
                return AWSTask(error:NSError(domain: "Facebook Login", code: -1 , userInfo: ["Facebook" : "No current Facebook access token"]))}
        }else if socialNetworkUsed == "Google" {
            let result = NSDictionary(dictionary: [AWSIdentityProviderGoogle: googleIDToken])
            print("Google results done \(result.allValues)")
            return AWSTask(result: result)
    
        } else {
            let result = NSDictionary(dictionary: [AWSIdentityProvider.self: facebookIDToken])
            return AWSTask(result: result)
        }
    }
    

    使用该代码我收到以下错误:

      

    java.lang.IllegalAccessError:尝试访问方法   B.method1(Ljava / lang ...)V来自A $ C级

    我没有任何compalition错误,但在运行时我收到错误。这里有什么问题?

    注意:B类定义位于jar文件中,该文件作为依赖项添加。 注意:当我调试时,当它调用C.someMethod时,它在框架面板上显示为

        public class D extends A{
            public static void main(arg){
                C.someMethod(new A(), args)
            }
        }
    
    
        public class A extends B{
             .....
        }
    
        public class B{
    
            public static final class C{
                 private B fieldB;
                 private static instance;
    
                 private C(B inB, String args){
                       this.fieldB = inB;
                       this.fieldB.method1(args) // illegalAccess
                 }
    
                 public static void someMethod(B b, String arg){
                        if(instanceC== null)
                               instanceC= new C(b, args)
                        else {..}
             }
    
             private void method1(String arg){}
        }
    

    不应该像下面那样吗?

    someMethod 1253, A$C
    

2 个答案:

答案 0 :(得分:1)

method1是C类的私有成员,只能由C类访问。您试图通过B类实例访问它,它会抛出IllegalAccessError

答案 1 :(得分:0)

最后我的问题已经解决,我清理了项目,并从一开始就重新启动并构建它可以工作。似乎JVM搞砸了。