java.lang.reflect.Field#getLong ( )源码实例Demo

下面列出了java.lang.reflect.Field#getLong ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: dble   文件: CustomMySQLHa.java
private long getPidOfLinux(boolean byHook) {
    long pid = -1;

    try {
        if (process.getClass().getName().equals("java.lang.UNIXProcess")) {
            Field f = process.getClass().getDeclaredField("pid");
            f.setAccessible(true);
            pid = f.getLong(process);
            f.setAccessible(false);
        }
    } catch (Exception e) {
        if (byHook) {
            System.out.println("getPidOfLinux failed:" + e);
        } else {
            LOGGER.warn("getPidOfLinux failed:", e);
        }
        pid = -1;
    }
    if (byHook) {
        System.out.println("python pid is " + pid);
    } else if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("python pid is " + pid);
    }

    return pid;
}
 
@Override
protected long getProcessId(Process process) {
    long result = super.getProcessId(process);
    if (result == 0L) {
        /* jtreg didn't find pid, most probably we are on JDK < 9
           there is no Process::getPid */
        if (HAS_NATIVE_LIBRARY && "windows".equals(OS.current().family)) {
            try {
                Field field = process.getClass().getDeclaredField("handle");
                boolean old = field.isAccessible();
                try {
                    field.setAccessible(true);
                    long handle = field.getLong(process);
                    result = getWin32Pid(handle);
                } finally {
                    field.setAccessible(old);
                }
            } catch (ReflectiveOperationException e) {
                e.printStackTrace(log);
            }
        }
    }
    return result;
}
 
源代码3 项目: genie   文件: JobProcessManagerImpl.java
private long getPid(final Process process) {
    long pid = -1;
    final String processClassName = process.getClass().getCanonicalName();
    try {
        if ("java.lang.UNIXProcess".equals(processClassName)) {
            final Field pidMemberField = process.getClass().getDeclaredField("pid");
            final boolean resetAccessible = pidMemberField.isAccessible();
            pidMemberField.setAccessible(true);
            pid = pidMemberField.getLong(process);
            pidMemberField.setAccessible(resetAccessible);
        } else {
            log.debug("Don't know how to access PID for class {}", processClassName);
        }
    } catch (final Throwable t) {
        log.warn("Failed to determine job process PID");
    }
    return pid;
}
 
protected static Integer windowsProcessId(Process process) {
  if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) {
    /* determine the pid on windows plattforms */
    try {
      Field f = process.getClass().getDeclaredField("handle");
      f.setAccessible(true);
      long handl = f.getLong(process);

      Kernel32 kernel = Kernel32.INSTANCE;
      WinNT.HANDLE handle = new WinNT.HANDLE();
      handle.setPointer(Pointer.createConstant(handl));
      int ret = kernel.GetProcessId(handle);
      log.debug("Detected pid: {}", ret);
      return ret;
    } catch (Throwable ex) {
      throw new RuntimeException("Cannot fetch windows pid!", ex);
    }
  }
  return null;
}
 
源代码5 项目: nifi   文件: OSUtils.java
/**
 * @param process NiFi Process Reference
 * @param logger  Logger Reference for Debug
 * @return        Returns pid or null in-case pid could not be determined
 * This method takes {@link Process} and {@link Logger} and returns
 * the platform specific Handle for Win32 Systems, a.k.a <b>pid</b>
 * In-case it fails to determine the pid, it will return Null.
 * Purpose for the Logger is to log any interaction for debugging.
 */
private static Long getWindowsProcessId(final Process process, final Logger logger) {
    /* determine the pid on windows plattforms */
    try {
        Field f = process.getClass().getDeclaredField("handle");
        f.setAccessible(true);
        long handl = f.getLong(process);

        Kernel32 kernel = Kernel32.INSTANCE;
        WinNT.HANDLE handle = new WinNT.HANDLE();
        handle.setPointer(Pointer.createConstant(handl));
        int ret = kernel.GetProcessId(handle);
        logger.debug("Detected pid: {}", ret);
        return Long.valueOf(ret);
    } catch (final IllegalAccessException | NoSuchFieldException nsfe) {
        logger.debug("Could not find PID for child process due to {}", nsfe);
    }
    return null;
}
 
源代码6 项目: buck   文件: ProcessHelper.java
@Nullable
private Long windowsProcessId(Object process) {
  Class<?> clazz = process.getClass();
  if (clazz.getName().equals("java.lang.Win32Process")
      || clazz.getName().equals("java.lang.ProcessImpl")) {
    try {
      Field f = clazz.getDeclaredField("handle");
      f.setAccessible(true);
      long peer = f.getLong(process);
      Pointer pointer = Pointer.createConstant(peer);
      WinNT.HANDLE handle = new WinNT.HANDLE(pointer);
      return (long) Kernel32.INSTANCE.GetProcessId(handle);
    } catch (Exception e) {
      LOG.warn(e, "Cannot get process id!");
    }
  }
  return null;
}
 
源代码7 项目: flink   文件: TestJvmProcess.java
/**
 * Gets the process ID, if possible. This method currently only work on UNIX-based
 * operating systems. On others, it returns {@code -1}.
 * 
 * @return The process ID, or -1, if the ID cannot be determined.
 */
public long getProcessId() {
	checkState(process != null, "process not started");

	try {
		Class<? extends Process> clazz = process.getClass();
		if (clazz.getName().equals("java.lang.UNIXProcess")) {
			Field pidField = clazz.getDeclaredField("pid");
			pidField.setAccessible(true);
			return pidField.getLong(process);
		} else if (clazz.getName().equals("java.lang.ProcessImpl")) {
			Method pid = clazz.getDeclaredMethod("pid");
			pid.setAccessible(true);
			return (long) pid.invoke(process);
		} else {
			return -1;
		}
	}
	catch (Throwable ignored) {
		return -1;
	}
}
 
源代码8 项目: openjdk-jdk9   文件: DisplayChangedTest.java
/**
 * Test fails if it throws any exception.
 *
 * @throws Exception
 */
private void init() throws Exception {

    if (!System.getProperty("os.name").startsWith("Windows")) {
        System.out.println("This is Windows only test.");
        return;
    }

    Frame frame = new Frame("AWT Frame");
    frame.pack();

    FramePeer frame_peer = AWTAccessor.getComponentAccessor()
            .getPeer(frame);
    Class comp_peer_class = Class.forName("sun.awt.windows.WComponentPeer");
    Field hwnd_field = comp_peer_class.getDeclaredField("hwnd");
    hwnd_field.setAccessible(true);
    long hwnd = hwnd_field.getLong(frame_peer);

    Class clazz = Class.forName("sun.awt.windows.WEmbeddedFrame");
    Constructor constructor = clazz
            .getConstructor(new Class[]{long.class});
    Frame embedded_frame = (Frame) constructor
            .newInstance(new Object[]{new Long(hwnd)});
    frame.setVisible(true);

    ComponentPeer peer = AWTAccessor.getComponentAccessor().getPeer(
            embedded_frame);
    Class peerClass = peer.getClass();
    Method displayChangedM = peerClass.getMethod("displayChanged",
            new Class[0]);
    displayChangedM.invoke(peer, null);
    embedded_frame.dispose();
    frame.dispose();

}
 
源代码9 项目: mnemonic   文件: Utils.java
/**
 * Gets the address value for the memory that backs a direct byte buffer.
 *
 * @param buffer
 *      A buffer to retrieve its address
 *
 * @return
 *      The system address for the buffers
 */
public static long getAddressFromDirectByteBuffer(ByteBuffer buffer) {
  try {
    Field addressField = Buffer.class.getDeclaredField("address");
    addressField.setAccessible(true);
    return addressField.getLong(buffer);
  } catch (Exception e) {
    throw new RuntimeException("Unable to address field from ByteBuffer", e);
  }
}
 
源代码10 项目: rocketmq-4.3.0   文件: ProducerManagerTest.java
@Test
public void scanNotActiveChannel() throws Exception {
    producerManager.registerProducer(group, clientInfo);
    assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNotNull();

    Field field = ProducerManager.class.getDeclaredField("CHANNEL_EXPIRED_TIMEOUT");
    field.setAccessible(true);
    long CHANNEL_EXPIRED_TIMEOUT = field.getLong(producerManager);
    clientInfo.setLastUpdateTimestamp(System.currentTimeMillis() - CHANNEL_EXPIRED_TIMEOUT - 10);
    when(channel.close()).thenReturn(mock(ChannelFuture.class));
    producerManager.scanNotActiveChannel();
    assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNull();
}
 
源代码11 项目: jvm-sandbox-repeater   文件: JavaSerializer.java
void serialize(AbstractHessianOutput out, Object obj, Field field)
  throws IOException
{
  long value = 0;

  try {
    value = field.getLong(obj);
  } catch (IllegalAccessException e) {
    log.log(Level.FINE, e.toString(), e);
  }

  out.writeLong(value);
}
 
源代码12 项目: rocketmq-read   文件: ProducerManagerTest.java
@Test
public void scanNotActiveChannel() throws Exception {
    producerManager.registerProducer(group, clientInfo);
    assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNotNull();

    Field field = ProducerManager.class.getDeclaredField("CHANNEL_EXPIRED_TIMEOUT");
    field.setAccessible(true);
    long CHANNEL_EXPIRED_TIMEOUT = field.getLong(producerManager);
    clientInfo.setLastUpdateTimestamp(System.currentTimeMillis() - CHANNEL_EXPIRED_TIMEOUT - 10);
    when(channel.close()).thenReturn(mock(ChannelFuture.class));
    producerManager.scanNotActiveChannel();
    assertThat(producerManager.getGroupChannelTable().get(group).get(channel)).isNull();
}
 
源代码13 项目: StaticLayoutView   文件: FpsCalculator.java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void start() {
	Log.d(TAG, "start vsync detect");
	if (mRunning) {
		return;
	}
	
	mRunning = true;

	syncCheckThread = new Thread(new Runnable() {
		@Override
		public void run() {
			for (;;) {
				if (!mRunning) {
					break;
				}
				syncCheckThread();
			}
		}
	});
	syncCheckThread.start();
	
	Choreographer chor = Choreographer.getInstance();
	Field field;
	try {
		field = chor.getClass().getDeclaredField("mFrameIntervalNanos");
		field.setAccessible(true);
		mFrameIntervalNanos = field.getLong(chor);
		Log.d(TAG, "mFrameIntervalNanos " + mFrameIntervalNanos);
	} catch (Exception e) {
		Log.e(TAG, "error: " + e.getMessage());
	}
	chor.postFrameCallback(frameCallback);

}
 
源代码14 项目: sofa-hessian   文件: JavaSerializer.java
void serialize(AbstractHessianOutput out, Object obj, Field field)
    throws IOException
{
    long value = 0;

    try {
        value = field.getLong(obj);
    } catch (IllegalAccessException e) {
        log.log(Level.FINE, e.toString(), e);
    }

    out.writeLong(value);
}
 
源代码15 项目: dubbo-hessian-lite   文件: JavaSerializer.java
@Override
void serialize(AbstractHessianOutput out, Object obj, Field field)
        throws IOException {
    long value = 0;

    try {
        value = field.getLong(obj);
    } catch (IllegalAccessException e) {
        log.log(Level.FINE, e.toString(), e);
    }

    out.writeLong(value);
}
 
源代码16 项目: GLEXP-Team-onebillion   文件: DBObject.java
private long getLongValue(String name)
{
    long result = 0;
    try {
        Field field = this.getClass().getDeclaredField(name);
        result =  field.getLong(this);
    } catch (Exception e) {
        throw new IllegalStateException(e);

    }
    return result;
}
 
源代码17 项目: FireFiles   文件: StorageUtils.java
private long getLong(Object object, String id) {
    long value = 0l;
    try {
        Field field = object.getClass().getDeclaredField(id);
        field.setAccessible(true);
        value = field.getLong(object);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return value;
}
 
源代码18 项目: FastTextView   文件: FpsCalculator.java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void start() {
	Log.d(TAG, "start vsync detect");
	if (mRunning) {
		return;
	}
	
	mRunning = true;

	syncCheckThread = new Thread(new Runnable() {
		@Override
		public void run() {
			for (;;) {
				if (!mRunning) {
					break;
				}
				syncCheckThread();
			}
		}
	});
	syncCheckThread.start();
	
	Choreographer chor = Choreographer.getInstance();
	Field field;
	try {
		field = chor.getClass().getDeclaredField("mFrameIntervalNanos");
		field.setAccessible(true);
		mFrameIntervalNanos = field.getLong(chor);
		Log.d(TAG, "mFrameIntervalNanos " + mFrameIntervalNanos);
	} catch (Exception e) {
		Log.e(TAG, "error: " + e.getMessage());
	}
	chor.postFrameCallback(frameCallback);

}
 
源代码19 项目: j2objc   文件: FieldTest.java
Object getField(char primitiveType, Object o, Field f,
        Class expected) {
    Object res = null;
    try {
        primitiveType = Character.toUpperCase(primitiveType);
        switch (primitiveType) {
        case 'I': // int
            res = new Integer(f.getInt(o));
            break;
        case 'J': // long
            res = new Long(f.getLong(o));
            break;
        case 'Z': // boolean
            res = new Boolean(f.getBoolean(o));
            break;
        case 'S': // short
            res = new Short(f.getShort(o));
            break;
        case 'B': // byte
            res = new Byte(f.getByte(o));
            break;
        case 'C': // char
            res = new Character(f.getChar(o));
            break;
        case 'D': // double
            res = new Double(f.getDouble(o));
            break;
        case 'F': // float
            res = new Float(f.getFloat(o));
            break;
        default:
            res = f.get(o);
        }
        // Since 2011, members are always accessible and throwing is optional
        assertTrue("expected " + expected + " for " + f.getName(),
                expected == null || expected == IllegalAccessException.class);
    } catch (Exception e) {
        if (expected == null) {
            fail("unexpected exception " + e);
        } else {
            assertTrue("expected exception "
                    + expected.getName() + " and got " + e, e
                    .getClass().equals(expected));
        }
    }
    return res;
}
 
源代码20 项目: netbeans   文件: LocalNativeProcess.java
private void createWin() throws IOException, InterruptedException {
    // Don't use shell wrapping on Windows...
    // Mostly this is because exec works not as expected and we cannot
    // control processes started with exec method....

    // Suspend is not supported on Windows.

    final ProcessBuilder pb = new ProcessBuilder(); // NOI18N

    final MacroMap jointEnv = MacroMap.forExecEnv(ExecutionEnvironmentFactory.getLocal());
    jointEnv.putAll(info.getEnvironment());

    if (isInterrupted()) {
        throw new InterruptedException();
    }

    if (info.isUnbuffer()) {
        UnbufferSupport.initUnbuffer(info.getExecutionEnvironment(), jointEnv);
    }

    pb.environment().clear();

    for (Entry<String, String> envEntry : jointEnv.entrySet()) {
        pb.environment().put(envEntry.getKey(), envEntry.getValue());
    }

    pb.redirectErrorStream(info.isRedirectError());
    pb.command(info.getCommand());

    if (LOG.isLoggable(Level.FINEST)) {
        LOG.finest(String.format("Command: %s", info.getCommand())); // NOI18N
    }

    String wdir = info.getWorkingDirectory(true);
    if (wdir != null) {
        File wd = new File(wdir);
        if (!wd.exists()) {
            throw new FileNotFoundException(loc("NativeProcess.noSuchDirectoryError.text", wd.getAbsolutePath())); // NOI18N
        }
        pb.directory(wd);
        if (LOG.isLoggable(Level.FINEST)) {
            LOG.finest(String.format("Working directory: %s", wdir)); // NOI18N
        }
    }

    process = pb.start();

    creation_ts = System.nanoTime();

    errorPipedOutputStream = new PipedOutputStream();
    errorPipedInputStream = new PipedInputStream(errorPipedOutputStream);

    setErrorStream(new SequenceInputStream(process.getErrorStream(), errorPipedInputStream));
    setInputStream(process.getInputStream());
    setOutputStream(process.getOutputStream());

    int newPid = 12345;

    try {
        String className = process.getClass().getName();
        if ("java.lang.Win32Process".equals(className) || "java.lang.ProcessImpl".equals(className)) { // NOI18N
            Field f = process.getClass().getDeclaredField("handle"); // NOI18N
            f.setAccessible(true);
            long phandle = f.getLong(process);

            Win32APISupport kernel = Win32APISupport.INSTANCE;
            Win32APISupport.HANDLE handle = new Win32APISupport.HANDLE();
            handle.setPointer(Pointer.createConstant(phandle));
            newPid = kernel.GetProcessId(handle);
        }
    } catch (Throwable e) {
    }

    ByteArrayInputStream bis = new ByteArrayInputStream(("" + newPid).getBytes()); // NOI18N

    readPID(bis);
}