Lookup in java

Lookup in java DEFAULT

Lookup an Object

To look up an object from the naming service, use and pass it the name of the object that you want to retrieve. Suppose that there is an object in the naming service with the name . To retrieve the object, you would write

Object obj = ctx.lookup("cn=Rosanna Lee,ou=People");

The type of object that is returned by depends both on the underlying naming system and on the data associated with the object itself. A naming system can contain many different types of objects, and a lookup of an object in different parts of the system might yield objects of different types. In this example, happens to be bound to a context object (). You can cast the result of to its target class.

For example, the following code looks up the object and casts it to .

import javax.naming.ldap.LdapContext; ... LdapContext ctx = (LdapContext) ctx.lookup("cn=Rosanna Lee,ou=People");

The complete example is in the file .

Diagram of Lookup example

There are two new static methods available in Java SE 6 to lookup a name:

These methods provide a shortcut way of looking up a name without instantiating an InitialContext.

« Previous • Trail • Next »

Sours: https://docs.oracle.com/javase/tutorial/jndi/ops/lookup.html

Java.io.ObjectStreamClass.lookup() Method



Description

The java.io.ObjectStreamClass.lookup(Class<?> cl) method finds the descriptor for a class that can be serialized. Creates an ObjectStreamClass instance if one does not exist yet for class. Null is returned if the specified class does not implement java.io.Serializable or java.io.Externalizable.

Declaration

Following is the declaration for java.io.ObjectStreamClass.lookup() method.

public static ObjectStreamClass lookup(Class<?> cl)

Parameters

cl − class for which to get the descriptor.

Return Value

This method returns the class descriptor for the specified class.

Exception

NA

Example

The following example shows the usage of java.io.ObjectStreamClass.lookup() method.

Live Demo

package com.tutorialspoint; import java.io.*; import java.util.Calendar; public class ObjectStreamClassDemo { public static void main(String[] args) { // create a new object stream class for Integers ObjectStreamClass osc = ObjectStreamClass.lookup(Integer.class); // get the name for Integers System.out.println("" + osc.getName()); // create a new object stream class for Calendar ObjectStreamClass osc2 = ObjectStreamClass.lookup(Calendar.class); // get the name for Calendar System.out.println("" + osc2.getName()); } }

Let us compile and run the above program, this will produce the following result −

java.lang.Integer java.util.Calendar

java_io_objectstreamclass.htm

Sours: https://www.tutorialspoint.com/java/io/objectstreamclass_lookup.htm
  1. Counselor confidentiality poster
  2. Propane tank rental home depot
  3. Workaholics best moments
  4. Go pure labs

Best Java code snippets using javax.naming.Context.lookup(Showing top 20 results out of 7,245)

Refine searchRefine arrow

  • Common ways to obtain Context

    private void myMethod () {

    Contextc=
    • Codota Iconnew InitialContext()
    • Codota IconHashtable env;new InitialContext(env)
    • Codota IconString scheme;Hashtable environment;NamingManager.getURLContext(scheme, environment)
    • Smart code suggestions by Tabnine

    }

    DataSource dataSource = null; try{ Context context = newInitialContext(); dataSource = (DataSource) context.lookup("Database"); } catch (NamingException e) { }
    publicstaticvoid destroyTable(String tableName) throws NamingException, SQLException { Context ctx = cache.getJNDIContext(); DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource"); Connection conn = ds.getConnection(); String sql = "drop table " + tableName; Statement sm = conn.createStatement(); sm.execute(sql); conn.close(); }
    ctx = (props != null) ? newInitialContext(props): newInitialContext(); ds = ctx.lookup(url); if (!isAlwaysLookup()) { this.datasource = ds; return (((XADataSource) ds).getXAConnection().getConnection()); } elseif (ds instanceof DataSource) { return ((DataSource) ds).getConnection(); } else { thrownew SQLException("Object at JNDI URL '" + url + "' is not a DataSource.");
    Context context = newInitialContext(); DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
    ctx = (props != null) ? newInitialContext(props): newInitialContext(); ds = ctx.lookup(url); if (!isAlwaysLookup()) { this.datasource = ds; return (((XADataSource) ds).getXAConnection().getConnection()); } elseif (ds instanceof DataSource) { return ((DataSource) ds).getConnection(); } else { thrownew SQLException("Object at JNDI URL '" + url + "' is not a DataSource.");
    publicstaticvoid listTableData(String tableName) throws NamingException, SQLException { Context ctx = cache.getJNDIContext(); DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource"); String sql = "select * from " + tableName; Connection conn = ds.getConnection(); Statement sm = conn.createStatement(); ResultSet rs = sm.executeQuery(sql); while (rs.next()) { System.out.println("id " + rs.getString(1) + " name " + rs.getString(2)); } rs.close(); conn.close(); }
    @Bean public DataSource dataSource() throws Exception { Context ctx = newInitialContext(); return (DataSource) ctx.lookup("java:jboss/datasources/mySQLDB"); }
    Context initCtx = newInitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup("jdbc/EmployeeDB"); Connection conn = ds.getConnection();
    publicint getRows(String tableName) throws NamingException, SQLException { Context ctx = cache.getJNDIContext(); DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource"); String sql = "select * from " + tableName; Connection conn = ds.getConnection(); Statement sm = conn.createStatement(); ResultSet rs = sm.executeQuery(sql); int counter = 0; while (rs.next()) { counter++; } rs.close(); conn.close(); return counter; }
    @Bean(destroyMethod = "") public DataSource dataSource() throws NamingException{ Context context = newInitialContext(); return (DataSource)context.lookup("jdbc.mydatasource"); }
    @Override public Connection get() { try { Context ctx = newInitialContext(); DataSource ds = (DataSource) ctx.lookup(jndiResource); Connection conn = ds.getConnection(); return conn; } catch (SQLException e) { thrownew SQLRuntimeException(e); } catch (NamingException e) { thrownew RuntimeException(e); } }
    publicstaticvoid createTable(String tableName) throws NamingException, SQLException { Context ctx = cache.getJNDIContext(); DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource"); String sql = "create table " + tableName + " (id integer NOT NULL, name varchar(50), CONSTRAINT the_key PRIMARY KEY(id))"; System.out.println(sql); Connection conn = ds.getConnection(); Statement sm = conn.createStatement(); sm.execute(sql); sm.close(); sm = conn.createStatement(); for (int i = 1; i <= 100; i++) { sql = "insert into " + tableName + " values (" + i + ",'name" + i + "')"; sm.addBatch(sql); System.out.println(sql); } sm.executeBatch(); conn.close(); }
    Context initialContext = newInitialContext(); String myvar = (String) initialContext.lookup("java:comp/env/myvar");
    publicstatic Statement open(String jndiPath) { try { Context ctx = newInitialContext(); DataSource ds = (DataSource) ctx.lookup(jndiPath); Connection conn = ds.getConnection(); return conn.createStatement(); } catch (NamingException e) { thrownew DukeException("No database configuration found via JNDI at " + jndiPath, e); } catch (SQLException e) { thrownew DukeException("Error connecting to database via " + jndiPath, e); } }
    publicint deleteRows(String tableName) throws NamingException, SQLException { Context ctx = cache.getJNDIContext(); DataSource da = (DataSource) ctx.lookup("java:/SimpleDataSource"); Connection conn = da.getConnection(); Statement stmt = conn.createStatement(); int rowsDeleted = 0; String sql = ""; sql = "select * from " + tableName; ResultSet rs = stmt.executeQuery(sql); if (rs.next()) { sql = "delete from " + tableName; rowsDeleted = stmt.executeUpdate(sql); } rs.close(); stmt.close(); conn.close(); return rowsDeleted; }
    import javax.naming.Context; import javax.naming.InitialContext; ... Context env = (Context)newInitialContext().lookup("java:comp/env"); String dbhost = (String)env.lookup("dbhost");
    public DB open(String jndiName) { checkExistingConnection(name); try { Context ctx = newInitialContext(); DataSource ds = (DataSource) ctx.lookup(jndiName); Connection connection = ds.getConnection(); LogFilter.log(LOGGER, LogLevel.DEBUG, "Opened connection: " + connection); ConnectionsAccess.attach(name, connection, jndiName); returnthis; } catch (Exception e) { thrownew InitException("Failed to connect to JNDI name: " + jndiName, e); } }
    publicboolean checkTableAgainstData(String tableName, String pattern) throws NamingException, SQLException { Context ctx = cache.getJNDIContext(); DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource"); boolean found = false; String id_str = ""; String sql = "select * from " + tableName; Connection conn = ds.getConnection(); Statement sm = conn.createStatement(); ResultSet rs = sm.executeQuery(sql); while (rs.next()) { System.out.println("id:" + rs.getString(1)); System.out.println("name:" + rs.getString(2)); id_str = rs.getString(1); if (id_str.equals(pattern)) { found = true; break; } elsecontinue; } rs.close(); conn.close(); return found; }
    Hashtable env = new Hashtable(5); env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); env.put(Context.PROVIDER_URL, "t3://localhost:7001"); Context ic = newInitialContext(env); FooHome fooHome = (FooHome)ic.lookup("MyBeans/FooHome"); Foo foo = fooHome.create(); foo.shoutFoo()
    public DB open(String jndiName, Properties jndiProperties) { checkExistingConnection(name); try { Context ctx = newInitialContext(jndiProperties); DataSource ds = (DataSource) ctx.lookup(jndiName); Connection connection = ds.getConnection(); LogFilter.log(LOGGER, LogLevel.DEBUG, "Opened connection: " + connection); ConnectionsAccess.attach(name, connection, jndiProperties.contains("url") ? jndiProperties.getProperty("url") : jndiName); returnthis; } catch (Exception e) { thrownew InitException("Failed to connect to JNDI name: " + jndiName, e); } }
    Sours: https://www.tabnine.com/code/java/methods/javax.naming.Context/lookup
    Lookup value by vin java . . . lookup code in java. lookup.java. below is the synta

    What this is

    This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

    Other links

    The source code

    /* * Sun Public License Notice * * The contents of this file are subject to the Sun Public License * Version 1.0 (the "License"). You may not use this file except in * compliance with the License. A copy of the License is available at * http://www.sun.com/ * * The Original Code is NetBeans. The Initial Developer of the Original * Code is Sun Microsystems, Inc. Portions Copyright 1997-2000 Sun * Microsystems, Inc. All Rights Reserved. */ package org.openide.util.lookup; import java.util.*; import org.openide.util.Lookup; import junit.framework.*; import org.netbeans.junit.*; /** * Tests for class SimpleLookup. * @author David Strupl */ public class SimpleLookupTest extends org.netbeans.junit.NbTestCase { public SimpleLookupTest(java.lang.String testName) { super(testName); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(new NbTestSuite(SimpleLookupTest.class)); } /** * Simple tests testing singleton lookup. */ public void testSingleton() { // Object orig = new Object(); Lookup p1 = Lookups.singleton(orig); Object obj = p1.lookup(Object.class); assertTrue(obj == orig); assertNull(p1.lookup(String.class)); assertTrue(orig == p1.lookup(Object.class)); // 2nd time, still the same? // Lookup p2 = Lookups.singleton("test"); assertNotNull(p2.lookup(Object.class)); assertNotNull(p2.lookup(String.class)); assertNotNull(p2.lookup(java.io.Serializable.class)); } /** * Simple tests testing fixed lookup. */ public void testFixed() { // Object[] orig = new Object[] { new Object(), new Object() }; Lookup p1 = Lookups.fixed(orig); Object obj = p1.lookup(Object.class); assertTrue(obj == orig[0] || obj == orig[1]); assertNull(p1.lookup(String.class)); // String[] s = new String[] { "test1", "test2" }; Lookup p2 = Lookups.fixed(s); Object obj2 = p2.lookup(Object.class); assertNotNull(obj2); if (obj2 != s[0] && obj2 != s[1]) { fail("Returned objects are not the originals"); } assertNotNull(p2.lookup(String.class)); assertNotNull(p2.lookup(java.io.Serializable.class)); Lookup.Template t = new Lookup.Template(String.class); Lookup.Result r = p2.lookup(t); Collection all = r.allInstances(); assertTrue(all.size() == 2); for (Iterator i = all.iterator(); i.hasNext(); ) { Object o = i.next(); if (o != s[0] && o != s[1]) { fail("allIinstances contains wrong objects"); } } } /** * Simple tests testing converting lookup. */ public void testConverting() { // Object[] orig = new Object[] { TestConvertor.TEST1, TestConvertor.TEST2 }; TestConvertor convertor = new TestConvertor(); Lookup p1 = Lookups.fixed(orig, convertor); assertNull("Converting from String to Integer - it should not find String in result", p1.lookup(String.class)); assertNotNull(p1.lookup(Integer.class)); assertNotNull(p1.lookup(Integer.class)); assertTrue("Convertor should be called only once.", convertor.getNumberOfConvertCalls() == 1); Lookup.Template t = new Lookup.Template(Integer.class); Lookup.Result r = p1.lookup(t); Collection all = r.allInstances(); assertTrue(all.size() == 2); for (Iterator i = all.iterator(); i.hasNext(); ) { Object o = i.next(); if (o != TestConvertor.t1 && o != TestConvertor.t2) { fail("allIinstances contains wrong objects"); } } } private static class TestConvertor implements InstanceContent.Convertor { static final String TEST1 = "test1"; static final Integer t1 = new Integer(1); static final String TEST2 = "test2"; static final Integer t2 = new Integer(2); private int numberOfConvertCalls = 0; public Object convert(Object obj) { numberOfConvertCalls++; if (obj.equals(TEST1)) { return t1; } if (obj.equals(TEST2)) { return t2; } throw new IllegalArgumentException(); } public String displayName(Object obj) { return obj.toString(); } public String id(Object obj) { if (obj.equals(TEST1)) { return TEST1; } if (obj.equals(TEST2)) { return TEST2; } return null; } public Class type(Object obj) { return Integer.class; } int getNumberOfConvertCalls() { return numberOfConvertCalls; } } public void testLookupItem() { SomeInst inst = new SomeInst(); Lookup.Item item = Lookups.lookupItem(inst, "XYZ"); assertTrue("Wrong instance", item.getInstance() == inst); assertTrue("Wrong instance class", item.getType() == inst.getClass()); assertEquals("Wrong id", "XYZ", item.getId()); item = Lookups.lookupItem(inst, null); assertNotNull("Id must never be null", item.getId()); } public void testLookupItemEquals() { SomeInst instA = new SomeInst(); SomeInst instB = new SomeInst(); Lookup.Item itemA = Lookups.lookupItem(instA, null); Lookup.Item itemB = Lookups.lookupItem(instB, null); assertTrue("Lookup items shouldn't be equal", !itemA.equals(itemB) && !itemB.equals(itemA)); itemA = Lookups.lookupItem(instA, null); itemB = Lookups.lookupItem(instA, null); // same instance assertTrue("Lookup items should be equal", itemA.equals(itemB) && itemB.equals(itemA)); assertTrue("Lookup items hashcode should be same", itemA.hashCode() == itemB.hashCode()); itemA = Lookups.lookupItem(new String("VOKURKA"), null); itemB = Lookups.lookupItem(new String("VOKURKA"), null); assertTrue("Lookup items shouldn't be equal (2)", !itemA.equals(itemB) && !itemB.equals(itemA)); } public void testAllClassesIssue42399 () throws Exception { Object[] arr = { "Ahoj", new Object () }; Lookup l = Lookups.fixed (arr); java.util.Set s = l.lookup (new Lookup.Template (Object.class)).allClasses (); assertEquals ("Two there", 2, s.size ()); assertTrue ("Contains Object.class", s.contains (Object.class)); assertTrue ("Contains string", s.contains (String.class)); } public void testLookupItemEarlyInitializationProblem() { InstanceContent ic = new InstanceContent(); AbstractLookup al = new AbstractLookup(ic); LI item = new LI(); ArrayList pairs1 = new ArrayList(); ArrayList pairs2 = new ArrayList(); assertEquals("Item's instance shouldn't be requested", 0, item.cnt); pairs1.add(new ItemPair(Lookups.lookupItem(new SomeInst(), null))); pairs1.add(new ItemPair(item)); pairs1.add(new ItemPair(Lookups.lookupItem(new Object(), null))); pairs2.add(new ItemPair(item)); pairs2.add(new ItemPair(Lookups.lookupItem(new Object(), null))); ic.setPairs(pairs1); ic.setPairs(pairs2); assertEquals("Item's instance shouldn't be requested when added to lookup", 0, item.cnt); LI item2 = (LI) al.lookup(LI.class); assertEquals("Item's instance should be requested", 1, item.cnt); } private static class SomeInst { } private static class LI extends Lookup.Item { public long cnt = 0; public String getDisplayName() { return getId(); } public String getId() { return getClass() + "@" + hashCode(); } public Object getInstance() { cnt++; return this; } public Class getType() { return getClass(); } } // End of LI class private static class ItemPair extends AbstractLookup.Pair { private AbstractLookup.Item item; public ItemPair (Lookup.Item i) { this.item = i; } protected boolean creatorOf(Object obj) { return item.getInstance() == obj; } public String getDisplayName() { return item.getDisplayName (); } public String getId() { return item.getId (); } public Object getInstance() { return item.getInstance (); } public Class getType() { return item.getType (); } protected boolean instanceOf(Class c) { return c.isAssignableFrom (getType ()); } public boolean equals (Object o) { if (o instanceof ItemPair) { ItemPair p = (ItemPair)o; return item.equals (p.item); } return false; } public int hashCode () { return item.hashCode (); } } // end of ItemPair }
    Sours: https://alvinalexander.com/java/jwarehouse/netbeans-src/openide/test/unit/src/org/openide/util/lookup/SimpleLookupTest.java.shtml

    In java lookup

    Best Java code snippets using java.rmi.Naming.lookup(Showing top 20 results out of 531)

    • Add the Codota plugin to your IDE and get smart completions

      private void myMethod () {

      }

      privatestaticsynchronizedvoid initialize() throws Exception { if (blackboard == null) { System.out.println( DUnitLauncher.RMI_PORT_PARAM + "=" + System.getProperty(DUnitLauncher.RMI_PORT_PARAM)); int namingPort = Integer.getInteger(DUnitLauncher.RMI_PORT_PARAM).intValue(); String name = "//localhost:" + namingPort + "/" + "InternalBlackboard"; try { blackboard = (InternalBlackboard) Naming.lookup(name); } catch (NotBoundException e) { blackboard = new InternalBlackboardImpl(); Naming.bind(name, blackboard); } } }
      stub = Naming.lookup(getServiceUrl());
      protected Object getRMIProxy() throws RemoteException, NotBoundException, MalformedURLException { Entry<String, Integer> entry = slaveChooser.chooseSlave(); String slaveIP = entry.getKey(); int port = entry.getValue(); System.out.println(getInvokeURL(slaveIP, port)); return Naming.lookup(getInvokeURL(slaveIP, port)); }
      stub = Naming.lookup(getServiceUrl());
      .lookup("//localhost:" + namingPort + "/" + DUnitLauncher.MASTER_PARAM); DUnitLauncher.init(holder); DUnitLauncher.locatorPort = holder.getLocatorPort();
      public CachePeer lookupRemoteCachePeer(String url) throws MalformedURLException, NotBoundException, RemoteException { LOG.debug("Lookup URL {}", url); CachePeer cachePeer = (CachePeer) Naming.lookup(url); return cachePeer; }
      protected RemoteBlockingQueue getQueue() throws Exception { return (RemoteBlockingQueue) Naming.lookup(this.queueURL); }
      @SuppressWarnings("unchecked") public <T> Remote<T> lookup(final String name) throws MalformedURLException, RemoteException, NotBoundException { return (Remote<T>) Naming.lookup(name); }
      public RMIMessageSender(String remoteRootURI) throws NotBoundException, MalformedURLException, RemoteException { this.remoteURI = remoteRootURI; destinationRMI = (RMIReceiveInterface) Naming.lookup(remoteURI); }
      public CachePeer lookupRemoteCachePeer(String url) throws MalformedURLException, NotBoundException, RemoteException { LOG.debug("Lookup URL {}", url); CachePeer cachePeer = (CachePeer) Naming.lookup(url); return cachePeer; }
      import java.rmi.Naming; publicclass RmiClient { publicstaticvoid main(String args[]) throws Exception { RmiServerIntf obj = (RmiServerIntf)Naming.lookup("//localhost/RmiServer"); System.out.println(obj.getMessage()); } }
      public CachePeer lookupRemoteCachePeer(String url) throws MalformedURLException, NotBoundException, RemoteException { LOG.debug("Lookup URL {}", url); CachePeer cachePeer = (CachePeer) Naming.lookup(url); return cachePeer; }
      publicvoid register(String url) throws RemoteException { try { RMIAdapterIn in = (RMIAdapterIn) Naming.lookup(url); if (in != null) inputs.put(url, in); } catch (Exception e) { e.printStackTrace(); } }
      protected RemoteRepository getRemoteRepository() throws RemoteException { try { return (RemoteRepository) Naming.lookup(url); } catch (MalformedURLException e) { thrownew RemoteException("Malformed URL: " + url, e); } catch (NotBoundException e) { thrownew RemoteException("No target found: " + url, e); } catch (ClassCastException e) { thrownew RemoteException("Unknown target: " + url, e); } }
      public EvalClient() { try { netConn = (NetEvaluation)Naming.lookup("//"+SERVER+"/EvalServer"); } catch (Exception e) { System.err.println("NetEvaluation exception: " + e.getMessage()); e.printStackTrace(); } }
      @SuppressWarnings("unchecked") publicstatic <S extends Service> S resolve( final String addr, finalint port, final String name ) throws NotBoundException, IOException, URISyntaxException { final String svcUri = getRemoteSvcUri(addr, port, name).toString(); return (S) Naming.lookup(svcUri); }
      privatevoid rebind() { if (System.getSecurityManager() == null) { System.setSecurityManager(new PESecurityManager()); } try { remoteHandler = (RemoteMessageHandler) Naming.lookup(bindname); System.out.println(remoteHandler.toString()); System.out.println("Channel proxy bound on " + bindname); retryFailures(); } catch (Exception e) { e.printStackTrace(); } }
      public ExampleRemoteClient() { try { rd = (RemoteDispatcher) Naming.lookup(RMI_URL); } catch (NotBoundException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } }
      @Override protectedvoid setUp() throws Exception { super.setUp(); showSystemState(getSystemPropertyFilter()); final String serviceUrl = getServiceUrl(); Sys.out("Phone Directory Service URL ({0})", serviceUrl); service = (PhoneDirectoryService) Naming.lookup(serviceUrl); }
      privateboolean connect(final String rmiHost) { try { _rmiHost = rmiHost; final Management management = (Management) Naming.lookup("//" + rmiHost + "/PersistitManagementServer"); setManagement(management); setFrameTitle(rmiHost); returntrue; } catch (final Exception e) { setManagement(null); showMessage(e, getProperty("ConnectionFailedMessage"), JOptionPane.ERROR_MESSAGE); returnfalse; } }
      Sours: https://www.tabnine.com/code/java/methods/java.rmi.Naming/lookup
      [Java] Dictionary lookup of a copied word
      Creates a lookup that wraps another one and filters out instances of specified classes. If you have a lookup and you want to remove all instances of ActionMap you can use: l = Lookups.exclude(lookup, ActionMap.class); Then anybody who asks for or subclass will get . Even if the original lookup contains the value. To create empty lookup (well, just an example, otherwise use ) one could use: Lookup.exclude(anyLookup, Object.class); as any instance in any lookup is of type Object and thus would be excluded.

      The complete behavior can be described as being a barrier. For an object not to be excluded, there has to be an inheritance path between the queried class and the actual class of the instance, that is not blocked by any of the excluded classes and the queried class cannot be subclass of an excluded class:

      interface A {} interface B {} class C implements A, B {} Object c = new C(); Lookup l1 = Lookups.singleton(c); Lookup l2 = Lookups.exclude(l1, A.class); assertNull("A is directly excluded", l2.lookup(A.class)); assertEquals("Returns C as A.class is not between B and C", c, l2.lookup(B.class)); For more info check the excluding lookup testsand the discussion in issue 53058.
      Parameters:
      - the original lookup that should be filtered
      - array of classes those instances should be excluded
      Since:
      5.4
      Sours: http://bits.netbeans.org/dev/javadoc/org-openide-util-lookup/org/openide/util/lookup/Lookups.html

      You will also like:

      A lookup objectis a factory for creating method handles, when the creation requires access checking. Method handles do not perform access checks when they are called, but rather when they are created. Therefore, method handle access restrictions must be enforced when a method handle is created. The caller class against which those restrictions are enforced is known as the lookup class.

      A lookup class which needs to create method handles will call to create a factory for itself. When the factory object is created, the identity of the lookup class is determined, and securely stored in the object. The lookup class (or its delegates) may then use factory methods on the object to create method handles for access-checked members. This includes all methods, constructors, and fields which are allowed to the lookup class, even private ones.

      The factory methods on a object correspond to all major use cases for methods, constructors, and fields. Here is a summary of the correspondence between these factory methods and the behavior the resulting method handles: Here, the type is the class or interface being searched for a member, documented as a parameter named in the lookup methods. The method or constructor type is composed from the return type and the sequence of argument types . Both and the field type are documented as a parameter named . The formal parameter stands for the self-reference of type ; if it is present, it is always the leading argument to the method handle invocation. (In the case of some members, may be restricted in type to the lookup class; see below.) The name stands for all the other method handle arguments. In the code examples for the Core Reflection API, the name stands for a null reference if the accessed method or field is static, and otherwise. The names , , and stand for reflective objects corresponding to the given members.

      In cases where the given member is of variable arity (i.e., a method or constructor) the returned method handle will also be of variable arity. In all other cases, the returned method handle will be of fixed arity.

      The equivalence between looked-up method handles and underlying class members can break down in a few ways:

      • If is not symbolically accessible from the lookup class's loader, the lookup can still succeed, even when there is no equivalent Java expression or bytecoded constant.
      • Likewise, if or is not symbolically accessible from the lookup class's loader, the lookup can still succeed. For example, lookups for and will always succeed, regardless of requested type.
      • If there is a security manager installed, it can forbid the lookup on various grounds (see below). By contrast, the instruction is not subject to security manager checks.

      Access checking

      Access checks are applied in the factory methods of , when a method handle is created. This is a key difference from the Core Reflection API, since performs access checking against every caller, on every call.

      All access checks start from a object, which compares its recorded lookup class against all requests to create method handles. A single object can be used to create any number of access-checked method handles, all checked against a single lookup class.

      A object can be shared with other trusted code, such as a metaobject protocol. A shared object delegates the capability to create method handles on private members of the lookup class. Even if privileged code uses the object, the access checking is confined to the privileges of the original lookup class.

      A lookup can fail, because the containing class is not accessible to the lookup class, or because the desired class member is missing, or because the desired class member is not accessible to the lookup class. In any of these cases, a will be thrown from the attempted lookup. The exact class will be one of the following:

      • NoSuchMethodException — if a method is requested but does not exist
      • NoSuchFieldException — if a field is requested but does not exist
      • IllegalAccessException — if the member exists but an access check fails

      In general, the conditions under which a method handle may be looked up for a method are exactly equivalent to the conditions under which the lookup class could have compiled and resolved a call to . Where the JVM would raise exceptions like , a method handle lookup will generally raise a corresponding checked exception, such as . And the effect of invoking the method handle resulting from the lookup is exactly equivalent to executing the compiled and resolved call to . The same point is true of fields and constructors.

      If the desired member is , the usual JVM rules apply, including the requirement that the lookup class must be either be in the same package as the desired member, or must inherit that member. (See the Java Virtual Machine Specification, sections 4.9.2, 5.4.3.5, and 6.4.) In addition, if the desired member is a non-static field or method in a different package, the resulting method handle may only be applied to objects of the lookup class or one of its subclasses. This requirement is enforced by narrowing the type of the leading parameter from (which will necessarily be a superclass of the lookup class) to the lookup class itself.

      The JVM represents constructors and static initializer blocks as internal methods with special names ( and ). The internal syntax of invocation instructions allows them to refer to such internal methods as if they were normal methods, but the JVM verifier rejects them. A lookup of such an internal method will produce a .

      In some cases, access between nested classes is obtained by the Java compiler by creating an wrapper method to access a private method of another class in the same top-level declaration. For example, a nested class can access private members within other related classes such as , , or , but the Java compiler may need to generate wrapper methods in those related classes. In such cases, a object on would be unable to those private members. A workaround for this limitation is the method, which can transform a lookup on into one on any of those other classes, without special elevation of privilege.

      Although bytecode instructions can only refer to classes in a related class loader, this API can search for methods in any class, as long as a reference to its object is available. Such cross-loader references are also possible with the Core Reflection API, and are impossible to bytecode instructions such as or . There is a security manager API to allow applications to check such cross-loader references. These checks apply to both the API and the Core Reflection API (as found on ).

      Access checks only apply to named and reflected methods, constructors, and fields. Other method handle creation methods, such as , do not require any access checks, and are done with static methods of , independently of any object.

      Security manager interactions

      If a security manager is present, member lookups are subject to additional checks. From one to four calls are made to the security manager. Any of these calls can refuse access by throwing a . Define as the security manager, as the containing class in which the member is being sought, and as the class in which the member is actually defined. The calls are made according to the following rules:
      • In all cases, is called.
      • If the class loader of the lookup class is not the same as or an ancestor of the class loader of , then is called, where is the package of .
      • If the retrieved member is not public, is called. (Note that might be the same as .) The default implementation of this security manager method inspects the stack to determine the original caller of the reflective request (such as ), and performs additional permission checks if the class loader of differs from the class loader of the class from which the reflective request came.
      • If the retrieved member is not public, and if and are in different class loaders, and if the class loader of the lookup class is not the same as or an ancestor of the class loader of , then is called, where is the package of .
      Sours: https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandles.Lookup.html


      823 824 825 826 827